'use client';

/**
 * 생산 현황판 메인 컴포넌트
 * API 연동 완료 (2025-12-26)
 *
 * 기능:
 * - 공장별 탭 필터링 (전체/스크린공장/슬랫공장/절곡공장)
 * - 통계 카드 6개 (전체작업/작업대기/작업중/작업완료/긴급/지연)
 * - 3컬럼 레이아웃 (긴급작업/지연작업/작업자별현황)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { usePermission } from '@/hooks/usePermission';
import { Factory, Clock, PlayCircle, CheckCircle2, AlertTriangle, Timer, Users } from 'lucide-react';
import { StatCardGridSkeleton } from '@/components/ui/skeleton';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { getPresetStyle } from '@/lib/utils/status-config';
import { Button } from '@/components/ui/button';
import { PageLayout } from '@/components/organisms/PageLayout';
import { toast } from 'sonner';
import { getDashboardData, getProcessOptions } from './actions';
import type { WorkOrder, WorkerStatus, DashboardStats, ProcessOption, TabOption } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { STATUS_LABELS } from './types';

export default function ProductionDashboard() {
  const router = useRouter();
  const screenPerm = usePermission('/production/screen');
  const workOrderPerm = usePermission('/production/work-order-management');

  // ===== 상태 관리 =====
  const [selectedTab, setSelectedTab] = useState<string>('all');
  const [, setProcessOptions] = useState<ProcessOption[]>([]);
  const [tabOptions, setTabOptions] = useState<TabOption[]>([{ value: 'all', label: '전체' }]);
  const [workOrders, setWorkOrders] = useState<WorkOrder[]>([]);
  const [workerStatus, setWorkerStatus] = useState<WorkerStatus[]>([]);
  const [stats, setStats] = useState<DashboardStats>({
    total: 0,
    waiting: 0,
    inProgress: 0,
    completed: 0,
    urgent: 0,
    delayed: 0,
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingProcesses, setIsLoadingProcesses] = useState(true);

  // ===== 공정 목록 로드 (최초 1회) =====
  useEffect(() => {
    const loadProcesses = async () => {
      setIsLoadingProcesses(true);
      try {
        const result = await getProcessOptions();
        if (result.success) {
          setProcessOptions(result.data);
          // 동적 탭 옵션 생성: 전체 + 공정 목록 (절곡 계열은 하위 탭으로 그룹화)
          const bendingParent: TabOption[] = [];
          const bendingChildren: TabOption[] = [];
          const otherTabs: TabOption[] = [];

          for (const p of result.data) {
            if (p.name.startsWith('절곡')) {
              if (p.name === '절곡') {
                bendingParent.push({ value: p.code, label: p.name });
              } else {
                // "절곡 (재공품-가이드레일)" → "가이드레일"
                const shortLabel = p.name.replace(/^절곡\s*\(재공품-?/, '').replace(/\)$/, '') || p.name;
                bendingChildren.push({ value: p.code, label: shortLabel });
              }
            } else {
              otherTabs.push({ value: p.code, label: p.name });
            }
          }

          // 절곡 부모에 하위 탭 연결
          const bendingTab: TabOption | null = bendingParent.length > 0
            ? { ...bendingParent[0], children: bendingChildren.length > 0 ? bendingChildren : undefined }
            : null;

          const dynamicTabs: TabOption[] = [
            { value: 'all', label: '전체' },
            ...otherTabs,
            ...(bendingTab ? [bendingTab] : []),
          ];
          setTabOptions(dynamicTabs);
        } else {
          toast.error(result.error || '공정 목록 조회에 실패했습니다.');
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[ProductionDashboard] loadProcesses error:', error);
        toast.error('공정 목록 로드 중 오류가 발생했습니다.');
      } finally {
        setIsLoadingProcesses(false);
      }
    };
    loadProcesses();
  }, []);

  // ===== 대시보드 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const processCode = selectedTab === 'all' ? undefined : selectedTab;
      const result = await getDashboardData(processCode);

      if (result.success) {
        setWorkOrders(result.workOrders);
        setWorkerStatus(result.workerStatus);
        setStats(result.stats);
      } else {
        toast.error(result.error || '데이터 조회에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[ProductionDashboard] loadData error:', error);
      toast.error('데이터 로드 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [selectedTab]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // ===== 필터링된 데이터 (탭에서 이미 필터링됨) =====
  const filteredOrders = workOrders;

  // ===== 긴급/지연/완료 작업 필터링 =====
  const urgentOrders = useMemo(
    () => filteredOrders.filter((o) => o.isUrgent).slice(0, 5),
    [filteredOrders]
  );
  const delayedOrders = useMemo(
    () => filteredOrders.filter((o) => o.isDelayed).slice(0, 5),
    [filteredOrders]
  );
  // 최근 완료 작업 (createdAt 기준 정렬, 최신 5건)
  const recentCompletedOrders = useMemo(
    () => filteredOrders
      .filter((o) => o.status === 'completed')
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      .slice(0, 5),
    [filteredOrders]
  );

  // ===== 핸들러 =====
  const handleOrderClick = (id: string) => {
    router.push(`/ko/production/work-orders/${id}?mode=view`);
  };

  const handleWorkerScreenClick = () => {
    router.push('/ko/production/worker-screen');
  };

  const handleWorkOrderListClick = () => {
    router.push('/ko/production/work-orders');
  };

  return (
    <PageLayout>
      <div className="space-y-6 overflow-x-hidden pb-20">
        {/* 헤더 */}
        <div className="space-y-3">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 shrink-0">
              <Factory className="h-5 w-5 text-primary" />
            </div>
            <div className="min-w-0">
              <h1 className="text-xl sm:text-2xl font-bold">생산 현황판</h1>
              <p className="text-sm text-muted-foreground">공장별 작업 현황을 확인합니다.</p>
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            {screenPerm.canView && (
              <Button variant="outline" size="sm" onClick={handleWorkerScreenClick}>
                <Users className="mr-1 h-4 w-4" />
                작업자 화면
              </Button>
            )}
            {workOrderPerm.canView && (
              <Button variant="outline" size="sm" onClick={handleWorkOrderListClick}>
                작업지시 목록
              </Button>
            )}
          </div>
        </div>

        {/* 공정별 탭 (동적 생성, 절곡은 depth 구조) */}
        <div className="space-y-1">
          <div className="overflow-x-auto -mx-3 px-3 md:mx-0 md:px-0">
            <Tabs value={
              // 하위 탭 선택 시 부모 탭을 활성화
              tabOptions.find(t => t.children?.some(c => c.value === selectedTab))?.value || selectedTab
            } onValueChange={(v) => {
              // 하위 탭이 있는 부모 선택 시 부모 값으로 설정
              setSelectedTab(v);
            }}>
              <TabsList className="w-max">
                {isLoadingProcesses ? (
                  <TabsTrigger value="all" className="px-6">전체</TabsTrigger>
                ) : (
                  tabOptions.map((tab) => (
                    <TabsTrigger key={tab.value} value={tab.value} className="px-4 sm:px-6">
                      {tab.label}
                    </TabsTrigger>
                  ))
                )}
              </TabsList>
            </Tabs>
          </div>

          {/* 하위 탭은 숨김 — 절곡 선택 시 전체(P-003)로 자동 동작 */}
        </div>

        {/* 로딩 상태 */}
        {isLoading && <StatCardGridSkeleton count={6} />}

        {/* 통계 카드 */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          <StatCard
            title="전체 작업"
            value={stats.total}
            icon={<Factory className="h-4 w-4" />}
            variant="default"
          />
          <StatCard
            title="작업 대기"
            value={stats.waiting}
            icon={<Clock className="h-4 w-4" />}
            variant="default"
          />
          <StatCard
            title="작업중"
            value={stats.inProgress}
            icon={<PlayCircle className="h-4 w-4" />}
            variant="blue"
          />
          <StatCard
            title="작업 완료"
            value={stats.completed}
            icon={<CheckCircle2 className="h-4 w-4" />}
            variant="green"
          />
          <StatCard
            title="긴급"
            value={stats.urgent}
            icon={<AlertTriangle className="h-4 w-4" />}
            variant="red"
          />
          <StatCard
            title="지연"
            value={stats.delayed}
            icon={<Timer className="h-4 w-4" />}
            variant="orange"
          />
        </div>

        {/* 4컬럼 레이아웃 */}
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6">
          {/* 긴급 작업 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <AlertTriangle className="h-4 w-4 text-red-500" />
                긴급 작업
                <Badge variant="destructive" className="ml-auto">
                  {stats.urgent}
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {urgentOrders.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">
                  긴급 작업이 없습니다.
                </p>
              ) : (
                urgentOrders.map((order) => (
                  <WorkOrderCard
                    key={order.id}
                    order={order}
                    onClick={() => handleOrderClick(order.id)}
                  />
                ))
              )}
            </CardContent>
          </Card>

          {/* 지연 작업 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <Timer className="h-4 w-4 text-orange-500" />
                지연 작업
                <Badge className={`ml-auto ${getPresetStyle('orange')} hover:bg-orange-100`}>
                  {stats.delayed}
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {delayedOrders.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">
                  지연 작업이 없습니다.
                </p>
              ) : (
                delayedOrders.map((order) => (
                  <WorkOrderCard
                    key={order.id}
                    order={order}
                    onClick={() => handleOrderClick(order.id)}
                    showDelay
                  />
                ))
              )}
            </CardContent>
          </Card>

          {/* 최근 완료 작업 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <CheckCircle2 className="h-4 w-4 text-green-500" />
                최근 완료
                <Badge className={`ml-auto ${getPresetStyle('success')} hover:bg-green-100`}>
                  {stats.completed}
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {recentCompletedOrders.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">
                  완료된 작업이 없습니다.
                </p>
              ) : (
                recentCompletedOrders.map((order) => (
                  <WorkOrderCard
                    key={order.id}
                    order={order}
                    onClick={() => handleOrderClick(order.id)}
                    showCompleted
                  />
                ))
              )}
            </CardContent>
          </Card>

          {/* 작업자별 현황 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base">
                <Users className="h-4 w-4 text-blue-500" />
                작업자별 현황
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {workerStatus.map((worker) => (
                  <WorkerStatusRow key={worker.id} worker={worker} />
                ))}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </PageLayout>
  );
}

// ===== 하위 컴포넌트 =====

interface StatCardProps {
  title: string;
  value: number;
  icon: React.ReactNode;
  variant: 'default' | 'blue' | 'green' | 'red' | 'orange';
}

function StatCard({ title, value, icon, variant }: StatCardProps) {
  const variantClasses = {
    default: 'bg-gray-50 text-gray-700',
    blue: 'bg-blue-50 text-blue-700',
    green: 'bg-green-50 text-green-700',
    red: 'bg-red-50 text-red-700',
    orange: 'bg-orange-50 text-orange-700',
  };

  return (
    <Card className={variantClasses[variant]}>
      <CardContent className="p-4">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium">{title}</span>
          {icon}
        </div>
        <p className="text-2xl font-bold mt-2">{value}</p>
      </CardContent>
    </Card>
  );
}

interface WorkOrderCardProps {
  order: WorkOrder;
  onClick: () => void;
  showDelay?: boolean;
  showCompleted?: boolean;
}

function WorkOrderCard({ order, onClick, showDelay, showCompleted }: WorkOrderCardProps) {
  const statusColors = {
    waiting: 'bg-gray-100 text-gray-800',
    inProgress: 'bg-blue-100 text-blue-800',
    completed: 'bg-green-100 text-green-800',
  };

  // 완료일 포맷팅 (createdAt을 완료일로 사용 - 실제로는 완료 시점의 timestamp 필요)
  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  };

  return (
    <div
      onClick={onClick}
      className="p-3 border rounded-lg hover:bg-accent cursor-pointer transition-colors"
    >
      {/* 1행: 작업번호 + 상태뱃지 + 공정뱃지 */}
      <div className="flex items-center gap-1.5 flex-wrap">
        <span className="text-xs font-medium text-muted-foreground">
          {order.orderNo}
        </span>
        {!showCompleted && (
          <Badge className={`text-xs ${statusColors[order.status]}`}>
            {STATUS_LABELS[order.status]}
          </Badge>
        )}
        <Badge variant="outline" className="text-xs">
          {order.processName}
        </Badge>
      </div>
      {/* 2행: 품명 + 우측 정보 */}
      <div className="flex items-center justify-between gap-2 mt-1">
        <p className="text-sm font-medium truncate min-w-0">{order.productName}</p>
        {showDelay && order.delayDays && (
          <span className="text-xs text-orange-600 font-medium shrink-0">+{order.delayDays}일 지연</span>
        )}
        {showCompleted && (
          <span className="text-xs text-green-600 shrink-0">{formatDate(order.createdAt)}</span>
        )}
        {order.isUrgent && !showDelay && !showCompleted && (
          <span className="text-xs text-muted-foreground shrink-0">순위 {order.priority}</span>
        )}
      </div>
      {/* 3행: 거래처 */}
      <p className="text-xs text-muted-foreground truncate">{order.client}</p>
      {order.assignees.length > 0 && (
        <p className="text-xs text-blue-600 truncate">담당: {order.assignees.join(', ')}</p>
      )}
      {order.instruction && !showCompleted && (
        <p className="text-xs text-muted-foreground mt-1 truncate">
          {order.instruction}
        </p>
      )}
    </div>
  );
}

interface WorkerStatusRowProps {
  worker: WorkerStatus;
}

function WorkerStatusRow({ worker }: WorkerStatusRowProps) {
  const _progressPercent = worker.assigned > 0
    ? Math.round((worker.completed / worker.assigned) * 100)
    : 0;

  return (
    <div className="flex items-center justify-between py-2 border-b last:border-0">
      <div className="flex items-center gap-3">
        <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-sm font-medium">
          {worker.name.charAt(0)}
        </div>
        <span className="text-sm font-medium">{worker.name}</span>
      </div>
      <div className="flex items-center gap-4 text-sm">
        <div className="text-center">
          <p className="text-xs text-muted-foreground">작업중</p>
          <p className="font-medium text-blue-600">{worker.inProgress}</p>
        </div>
        <div className="text-center">
          <p className="text-xs text-muted-foreground">완료</p>
          <p className="font-medium text-green-600">{worker.completed}</p>
        </div>
        <div className="text-center">
          <p className="text-xs text-muted-foreground">배정</p>
          <p className="font-medium">{worker.assigned}</p>
        </div>
      </div>
    </div>
  );
}