'use client';

import { useState } from 'react';
import {
  Factory,
  AlertTriangle,
  Star,
  Layers,
  Users,
  Truck,
  Package,
  ClipboardList,
  ListTodo,
  Play,
  CheckCircle2,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { formatKoreanAmount } from '@/lib/utils/amount';
import { CollapsibleDashboardCard } from '../components';
import type { DailyProductionData } from '../types';

// 출고 현황 독립 섹션
interface ShipmentSectionProps {
  data: DailyProductionData;
}

export function ShipmentSection({ data }: ShipmentSectionProps) {
  return (
    <CollapsibleDashboardCard
      icon={<Truck style={{ color: '#ffffff' }} className="h-5 w-5" />}
      title="출고 현황"
      subtitle="예상 출고 정보"
    >
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div className="rounded-xl border p-4 bg-blue-50 dark:bg-blue-900/30 border-blue-200 dark:border-blue-800">
            <div className="flex items-center gap-2 mb-3">
              <Package className="h-4 w-4 text-blue-500" />
              <span className="text-sm font-medium text-muted-foreground">예상 출고 (7일 이내)</span>
            </div>
            <p className="text-xl font-bold text-foreground mb-1">{formatKoreanAmount(data.shipment.expectedAmount)}</p>
            <p className="text-xs text-muted-foreground">{data.shipment.expectedCount}건</p>
          </div>
          <div className="rounded-xl border p-4 bg-green-50 dark:bg-green-900/30 border-green-200 dark:border-green-800">
            <div className="flex items-center gap-2 mb-3">
              <Truck className="h-4 w-4 text-green-500" />
              <span className="text-sm font-medium text-muted-foreground">예상 출고 (30일 이내)</span>
            </div>
            <p className="text-xl font-bold text-foreground mb-1">{formatKoreanAmount(data.shipment.actualAmount)}</p>
            <p className="text-xs text-muted-foreground">{data.shipment.actualCount}건</p>
          </div>
        </div>
    </CollapsibleDashboardCard>
  );
}

interface DailyProductionSectionProps {
  data: DailyProductionData;
  showShipment?: boolean;
}

const PROCESS_TAB_NAMES: Record<string, string> = {
  '스크린': '스크린 공정',
  '슬랫': '슬랫 공정',
  '절곡': '절곡 공정',
};

export function DailyProductionSection({ data, showShipment = true }: DailyProductionSectionProps) {
  const [activeTab, setActiveTab] = useState(data.processes[0]?.processName ?? '');

  return (
    <div className="space-y-6">
    <CollapsibleDashboardCard
      icon={<Factory style={{ color: '#ffffff' }} className="h-5 w-5" />}
      title="당일 생산 현황"
      subtitle={data.date}
      rightElement={
        <Badge
          className="bg-violet-500 text-white border-none hover:opacity-90"
        >
          실시간
        </Badge>
      }
    >
        {/* 공정 탭 */}
        {data.processes.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
            <Factory className="h-10 w-10 mb-3 opacity-30" />
            <p className="text-sm">오늘 등록된 작업 지시가 없습니다.</p>
          </div>
        ) : (
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="mb-4">
            {data.processes.map((process) => (
              <TabsTrigger key={process.processName} value={process.processName}>
                {PROCESS_TAB_NAMES[process.processName] ?? `${process.processName} 공정`}
              </TabsTrigger>
            ))}
          </TabsList>

          {data.processes.map((process) => (
            <TabsContent key={process.processName} value={process.processName}>
              {/* 요약 카드: 전체 작업 / 할일 / 작업중 / 완료 */}
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-4">
                <div className="flex items-center gap-2 rounded-lg border border-border p-3">
                  <ClipboardList className="h-4 w-4 text-muted-foreground shrink-0" />
                  <div>
                    <p className="text-[11px] text-muted-foreground">전체 작업</p>
                    <p className="text-sm font-bold text-foreground">{process.totalWork}건</p>
                  </div>
                </div>
                <div className="flex items-center gap-2 rounded-lg border border-border p-3">
                  <ListTodo className="h-4 w-4 text-orange-500 shrink-0" />
                  <div>
                    <p className="text-[11px] text-muted-foreground">할일</p>
                    <p className="text-sm font-bold text-foreground">{process.todo}건</p>
                  </div>
                </div>
                <div className="flex items-center gap-2 rounded-lg border border-border p-3">
                  <Play className="h-4 w-4 text-blue-500 shrink-0" />
                  <div>
                    <p className="text-[11px] text-muted-foreground">작업중</p>
                    <p className="text-sm font-bold text-foreground">{process.inProgress}건</p>
                  </div>
                </div>
                <div className="flex items-center gap-2 rounded-lg border border-border p-3">
                  <CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />
                  <div>
                    <p className="text-[11px] text-muted-foreground">완료</p>
                    <p className="text-sm font-bold text-foreground">{process.completed}건</p>
                  </div>
                </div>
              </div>

              {/* 4열 카드 레이아웃: 긴급 / 우선 / 일반 / 작업자 현황 - 모바일 가로스크롤 */}
              <div className="-mx-6 px-6 flex gap-4 overflow-x-auto pb-2 lg:mx-0 lg:px-0 lg:grid lg:grid-cols-4 lg:overflow-visible lg:pb-0">
                {/* 긴급 */}
                <div className="min-w-[200px] shrink-0 lg:min-w-0 lg:shrink border border-border rounded-lg overflow-hidden">
                  <div className="p-3 border-b border-border bg-red-50 dark:bg-red-900/30">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <AlertTriangle className="h-3.5 w-3.5 text-red-500" />
                        <span className="text-xs font-semibold text-red-600 dark:text-red-400">긴급</span>
                      </div>
                      <span className="text-sm font-bold text-foreground">{process.urgent}건</span>
                    </div>
                  </div>
                  <div className="p-2 space-y-2 max-h-[240px] overflow-y-auto">
                    {process.workItems
                      .filter((item) => item.status === '진행중')
                      .slice(0, process.urgent)
                      .map((item) => (
                        <div key={item.id} className="border border-border rounded p-2 hover:bg-muted/50 cursor-pointer transition-colors">
                          <p className="text-xs font-medium text-foreground truncate">{item.client}</p>
                          <p className="text-[11px] text-muted-foreground">{item.product}</p>
                          <p className="text-[11px] text-muted-foreground">{item.quantity}건</p>
                        </div>
                      ))}
                  </div>
                </div>

                {/* 우선 */}
                <div className="min-w-[200px] shrink-0 lg:min-w-0 lg:shrink border border-border rounded-lg overflow-hidden">
                  <div className="p-3 border-b border-border bg-orange-50 dark:bg-orange-900/30">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <Star className="h-3.5 w-3.5 text-orange-500" />
                        <span className="text-xs font-semibold text-orange-600 dark:text-orange-400">우선</span>
                      </div>
                      <span className="text-sm font-bold text-foreground">{process.subLine}건</span>
                    </div>
                  </div>
                  <div className="p-2 space-y-2 max-h-[240px] overflow-y-auto">
                    {process.workItems
                      .filter((item) => item.status === '대기')
                      .slice(0, process.subLine)
                      .map((item) => (
                        <div key={item.id} className="border border-border rounded p-2 hover:bg-muted/50 cursor-pointer transition-colors">
                          <p className="text-xs font-medium text-foreground truncate">{item.client}</p>
                          <p className="text-[11px] text-muted-foreground">{item.product}</p>
                          <p className="text-[11px] text-muted-foreground">{item.quantity}건</p>
                        </div>
                      ))}
                  </div>
                </div>

                {/* 일반 */}
                <div className="min-w-[200px] shrink-0 lg:min-w-0 lg:shrink border border-border rounded-lg overflow-hidden">
                  <div className="p-3 border-b border-border bg-blue-50 dark:bg-blue-900/30">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <Layers className="h-3.5 w-3.5 text-blue-500" />
                        <span className="text-xs font-semibold text-blue-600 dark:text-blue-400">일반</span>
                      </div>
                      <span className="text-sm font-bold text-foreground">{process.regular}건</span>
                    </div>
                  </div>
                  <div className="p-2 space-y-2 max-h-[240px] overflow-y-auto">
                    {process.workItems
                      .slice(0, process.regular)
                      .map((item) => (
                        <div key={item.id} className="border border-border rounded p-2 hover:bg-muted/50 cursor-pointer transition-colors">
                          <p className="text-xs font-medium text-foreground truncate">{item.client}</p>
                          <p className="text-[11px] text-muted-foreground">{item.product}</p>
                          <p className="text-[11px] text-muted-foreground">{item.quantity}건</p>
                        </div>
                      ))}
                  </div>
                </div>

                {/* 작업자 현황 */}
                <div className="min-w-[200px] shrink-0 lg:min-w-0 lg:shrink border border-border rounded-lg overflow-hidden">
                  <div className="p-3 border-b border-border bg-green-50 dark:bg-green-900/30">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <Users className="h-3.5 w-3.5 text-green-500" />
                        <span className="text-xs font-semibold text-green-600 dark:text-green-400">작업자 현황</span>
                      </div>
                      <span className="text-sm font-bold text-foreground">{process.workerCount}명</span>
                    </div>
                  </div>
                  <div className="p-2 space-y-2 max-h-[240px] overflow-y-auto">
                    {process.workers.map((worker, idx) => (
                      <div key={idx} className="border border-border rounded p-2">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-xs font-medium text-foreground">{worker.name}</span>
                          <span className="text-[11px] text-muted-foreground">{worker.completed}/{worker.assigned}건</span>
                        </div>
                        <div className="flex items-center gap-1.5">
                          <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                            <div
                              className="h-full rounded-full"
                              style={{
                                width: `${worker.rate}%`,
                                backgroundColor: worker.rate >= 80 ? '#22c55e' : worker.rate >= 50 ? '#f59e0b' : '#ef4444',
                              }}
                            />
                          </div>
                          <span className="text-[10px] text-muted-foreground min-w-[28px] text-right">{worker.rate}%</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </TabsContent>
          ))}
        </Tabs>
        )}

    </CollapsibleDashboardCard>

    {/* 출고 현황 (별도 카드) */}
    {showShipment && (
      <CollapsibleDashboardCard
        icon={<Truck style={{ color: '#ffffff' }} className="h-5 w-5" />}
        title="출고 현황"
        subtitle="예상 출고 정보"
      >
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="rounded-xl border p-4 bg-blue-50 dark:bg-blue-900/30 border-blue-200 dark:border-blue-800">
              <div className="flex items-center gap-2 mb-3">
                <Package className="h-4 w-4 text-blue-500" />
                <span className="text-sm font-medium text-muted-foreground">예상 출고 (7일 이내)</span>
              </div>
              <p className="text-xl font-bold text-foreground mb-1">{formatKoreanAmount(data.shipment.expectedAmount)}</p>
              <p className="text-xs text-muted-foreground">{data.shipment.expectedCount}건</p>
            </div>
            <div className="rounded-xl border p-4 bg-green-50 dark:bg-green-900/30 border-green-200 dark:border-green-800">
              <div className="flex items-center gap-2 mb-3">
                <Truck className="h-4 w-4 text-green-500" />
                <span className="text-sm font-medium text-muted-foreground">예상 출고 (30일 이내)</span>
              </div>
              <p className="text-xl font-bold text-foreground mb-1">{formatKoreanAmount(data.shipment.actualAmount)}</p>
              <p className="text-xs text-muted-foreground">{data.shipment.actualCount}건</p>
            </div>
          </div>
      </CollapsibleDashboardCard>
    )}
    </div>
  );
}
