/**
 * 생산관리 - 디자인시스템 표준 패턴 적용
 * 
 * 표준 구조:
 * - PageLayout
 * - PageHeader (title + description + icon + actions)
 * - StatCards (4개 통계)
 * - Tabs (스크린, 슬랫, 절곡, 재고)
 */

import { useState, useMemo } from "react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { SearchFilter } from "./organisms/SearchFilter";
import { DataTable, Column } from "./organisms/DataTable";
import { EmptyState } from "./organisms/EmptyState";
import { Card, CardContent } from "./ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Label } from "./ui/label";
import {
  Factory,
  FileText,
  PlayCircle,
  TrendingDown,
  TrendingUp,
  Plus,
  Download,
  Eye,
  CheckCircle,
  Clock,
  AlertCircle,
} from "lucide-react";
import { toast } from "sonner@2.0.3";

interface WorkOrder {
  id: string;
  workOrderNumber: string;
  productionType: "스크린" | "슬랫" | "절곡" | "재고";
  productCode: string;
  productName: string;
  specification: string;
  targetQuantity: number;
  completedQuantity: number;
  unit: string;
  startDate: string;
  dueDate: string;
  status: "대기" | "진행중" | "완료" | "중단";
  worker: string;
  priority: "높음" | "보통" | "낮음";
  note?: string;
}

export function ProductionManagement() {
  const [activeTab, setActiveTab] = useState<"screen" | "slat" | "bending" | "stock">("screen");
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false);
  const [selectedWorkOrder, setSelectedWorkOrder] = useState<WorkOrder | null>(null);

  // Mock 데이터
  const workOrders: WorkOrder[] = [
    {
      id: "1",
      workOrderNumber: "WO-250118-001",
      productionType: "스크린",
      productCode: "SCR-001",
      productName: "스크린 프레임",
      specification: "1200*2000",
      targetQuantity: 50,
      completedQuantity: 35,
      unit: "EA",
      startDate: "2025-01-18",
      dueDate: "2025-01-25",
      status: "진행중",
      worker: "김작업",
      priority: "높음",
    },
    {
      id: "2",
      workOrderNumber: "WO-250118-002",
      productionType: "슬랫",
      productCode: "SLT-001",
      productName: "슬랫",
      specification: "80mm",
      targetQuantity: 100,
      completedQuantity: 100,
      unit: "EA",
      startDate: "2025-01-15",
      dueDate: "2025-01-18",
      status: "완료",
      worker: "이작업",
      priority: "보통",
    },
    {
      id: "3",
      workOrderNumber: "WO-250118-003",
      productionType: "절곡",
      productCode: "BND-001",
      productName: "절곡 부품",
      specification: "L형 90도",
      targetQuantity: 200,
      completedQuantity: 0,
      unit: "EA",
      startDate: "2025-01-20",
      dueDate: "2025-01-27",
      status: "대기",
      worker: "박작업",
      priority: "보통",
    },
    {
      id: "4",
      workOrderNumber: "WO-250118-004",
      productionType: "재고",
      productCode: "STK-001",
      productName: "재고 보충품",
      specification: "표준",
      targetQuantity: 150,
      completedQuantity: 75,
      unit: "EA",
      startDate: "2025-01-17",
      dueDate: "2025-01-24",
      status: "진행중",
      worker: "최작업",
      priority: "낮음",
    },
    {
      id: "5",
      workOrderNumber: "WO-250118-005",
      productionType: "스크린",
      productCode: "SCR-002",
      productName: "스크린 방충망",
      specification: "1500*2500",
      targetQuantity: 30,
      completedQuantity: 15,
      unit: "EA",
      startDate: "2025-01-18",
      dueDate: "2025-01-22",
      status: "중단",
      worker: "정작업",
      priority: "높음",
      note: "자재 부족으로 일시 중단"
    },
  ];

  // 통계 계산
  const stats = useMemo(() => {
    const filteredByTab = workOrders.filter(wo => {
      if (activeTab === "screen") return wo.productionType === "스크린";
      if (activeTab === "slat") return wo.productionType === "슬랫";
      if (activeTab === "bending") return wo.productionType === "절곡";
      if (activeTab === "stock") return wo.productionType === "재고";
      return true;
    });

    const totalCompleted = filteredByTab.reduce((sum, wo) => sum + wo.completedQuantity, 0);
    const totalTarget = filteredByTab.reduce((sum, wo) => sum + wo.targetQuantity, 0);
    const completionRate = totalTarget > 0 ? ((totalCompleted / totalTarget) * 100).toFixed(1) : "0";

    return [
      {
        label: "작업지시",
        value: filteredByTab.length,
        icon: FileText,
        iconColor: "text-blue-600"
      },
      {
        label: "진행중",
        value: filteredByTab.filter(wo => wo.status === "진행중").length,
        icon: PlayCircle,
        iconColor: "text-orange-600"
      },
      {
        label: "완료",
        value: filteredByTab.filter(wo => wo.status === "완료").length,
        icon: CheckCircle,
        iconColor: "text-green-600"
      },
      {
        label: "완료율",
        value: `${completionRate}%`,
        icon: TrendingUp,
        iconColor: "text-purple-600"
      }
    ];
  }, [workOrders, activeTab]);

  // 테이블 컬럼
  const columns: Column<WorkOrder>[] = [
    {
      key: "workOrderNumber",
      label: "작업지시번호",
      render: (wo) => (
        <span className="font-mono text-sm">{wo.workOrderNumber}</span>
      )
    },
    {
      key: "productName",
      label: "제품",
      render: (wo) => (
        <div>
          <div className="font-medium">{wo.productName}</div>
          <div className="text-xs text-muted-foreground">{wo.productCode}</div>
        </div>
      )
    },
    {
      key: "specification",
      label: "규격",
    },
    {
      key: "progress",
      label: "진행률",
      render: (wo) => {
        const progress = wo.targetQuantity > 0 
          ? ((wo.completedQuantity / wo.targetQuantity) * 100).toFixed(0)
          : 0;
        return (
          <div>
            <div className="flex items-center gap-2">
              <div className="flex-1 bg-muted rounded-full h-2">
                <div
                  className="bg-primary h-2 rounded-full"
                  style={{ width: `${progress}%` }}
                />
              </div>
              <span className="text-sm">{progress}%</span>
            </div>
            <div className="text-xs text-muted-foreground mt-1">
              {wo.completedQuantity} / {wo.targetQuantity} {wo.unit}
            </div>
          </div>
        );
      }
    },
    {
      key: "dueDate",
      label: "납기일",
      render: (wo) => {
        const isOverdue = new Date(wo.dueDate) < new Date() && wo.status !== "완료";
        return (
          <div className={isOverdue ? "text-red-600" : ""}>
            {wo.dueDate}
            {isOverdue && <AlertCircle className="w-3 h-3 inline ml-1" />}
          </div>
        );
      }
    },
    {
      key: "worker",
      label: "작업자",
    },
    {
      key: "priority",
      label: "우선순위",
      render: (wo) => getPriorityBadge(wo.priority)
    },
    {
      key: "status",
      label: "상태",
      render: (wo) => getStatusBadge(wo.status)
    },
  ];

  // 필터링
  const filteredWorkOrders = useMemo(() => {
    return workOrders.filter(wo => {
      // 탭 필터
      const matchesTab =
        (activeTab === "screen" && wo.productionType === "스크린") ||
        (activeTab === "slat" && wo.productionType === "슬랫") ||
        (activeTab === "bending" && wo.productionType === "절곡") ||
        (activeTab === "stock" && wo.productionType === "재고");

      // 검색 필터
      const matchesSearch = searchTerm === "" ||
        wo.workOrderNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        wo.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        wo.productCode.toLowerCase().includes(searchTerm.toLowerCase());

      // 상태 필터
      const matchesStatus = filterStatus === "all" || wo.status === filterStatus;

      return matchesTab && matchesSearch && matchesStatus;
    });
  }, [workOrders, activeTab, searchTerm, filterStatus]);

  // 상태 뱃지
  const getStatusBadge = (status: string) => {
    const variants: { [key: string]: { variant: any; className: string } } = {
      '대기': { variant: "outline", className: "bg-gray-50 text-gray-700 border-gray-200" },
      '진행중': { variant: "outline", className: "bg-orange-50 text-orange-700 border-orange-200" },
      '완료': { variant: "outline", className: "bg-green-50 text-green-700 border-green-200" },
      '중단': { variant: "outline", className: "bg-red-50 text-red-700 border-red-200" },
    };
    const config = variants[status] || variants['대기'];
    return <Badge variant={config.variant} className={config.className}>{status}</Badge>;
  };

  // 우선순위 뱃지
  const getPriorityBadge = (priority: string) => {
    const variants: { [key: string]: { variant: any; className: string } } = {
      '높음': { variant: "outline", className: "bg-red-50 text-red-700 border-red-200" },
      '보통': { variant: "outline", className: "bg-blue-50 text-blue-700 border-blue-200" },
      '낮음': { variant: "outline", className: "bg-gray-50 text-gray-700 border-gray-200" },
    };
    const config = variants[priority] || variants['보통'];
    return <Badge variant={config.variant} className={config.className}>{priority}</Badge>;
  };

  const handleView = (workOrder: WorkOrder) => {
    setSelectedWorkOrder(workOrder);
    setIsDetailDialogOpen(true);
  };

  const handleNewWorkOrder = () => {
    toast.info("작업지시 등록 기능 (개발 예정)");
  };

  const tabLabels = {
    screen: "스크린",
    slat: "슬랫",
    bending: "절곡",
    stock: "재고"
  };

  return (
    <PageLayout>
      <PageHeader
        title="생산관리"
        description="작업지시 및 공정진행 관리"
        icon={Factory}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => toast.info("Excel 다운로드 (개발 예정)")}>
              <Download className="w-4 h-4 mr-2" />
              Excel 다운로드
            </Button>
            <Button onClick={handleNewWorkOrder}>
              <Plus className="w-4 h-4 mr-2" />
              작업지시 등록
            </Button>
          </div>
        }
      />

      <StatCards stats={stats} />

      {/* 생산 유형 탭 */}
      <Card>
        <CardContent className="pt-6">
          <Tabs value={activeTab} onValueChange={(v: any) => setActiveTab(v)} className="space-y-4">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="screen">스크린</TabsTrigger>
              <TabsTrigger value="slat">슬랫</TabsTrigger>
              <TabsTrigger value="bending">절곡</TabsTrigger>
              <TabsTrigger value="stock">재고</TabsTrigger>
            </TabsList>

            <TabsContent value={activeTab} className="space-y-4">
              {/* 검색 및 필터 */}
              <div className="flex flex-col md:flex-row gap-4">
                <div className="flex-1">
                  <SearchFilter
                    searchValue={searchTerm}
                    onSearchChange={setSearchTerm}
                    searchPlaceholder="작업지시번호, 제품명으로 검색..."
                  />
                </div>
                <div className="w-full md:w-48">
                  <Select value={filterStatus} onValueChange={setFilterStatus}>
                    <SelectTrigger>
                      <SelectValue placeholder="상태 필터" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체 상태</SelectItem>
                      <SelectItem value="대기">대기</SelectItem>
                      <SelectItem value="진행중">진행중</SelectItem>
                      <SelectItem value="완료">완료</SelectItem>
                      <SelectItem value="중단">중단</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 작업지시 목록 */}
              {filteredWorkOrders.length === 0 ? (
                <EmptyState
                  icon={Factory}
                  title={`${tabLabels[activeTab]} 작업지시가 없습니다`}
                  description="새로운 작업지시를 등록해보세요"
                  action={{
                    label: "작업지시 등록",
                    onClick: handleNewWorkOrder
                  }}
                />
              ) : (
                <DataTable
                  columns={columns}
                  data={filteredWorkOrders}
                  keyField="id"
                  onRowClick={handleView}
                />
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* 상세보기 다이얼로그 */}
      <Dialog open={isDetailDialogOpen} onOpenChange={setIsDetailDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>작업지시 상세 정보</DialogTitle>
            <DialogDescription>
              작업지시번호: {selectedWorkOrder?.workOrderNumber}
            </DialogDescription>
          </DialogHeader>

          {selectedWorkOrder && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground">생산 유형</Label>
                  <div className="mt-1">
                    <Badge>{selectedWorkOrder.productionType}</Badge>
                  </div>
                </div>
                <div>
                  <Label className="text-muted-foreground">상태</Label>
                  <div className="mt-1">
                    {getStatusBadge(selectedWorkOrder.status)}
                  </div>
                </div>
                <div>
                  <Label className="text-muted-foreground">제품코드</Label>
                  <div className="mt-1 font-mono">{selectedWorkOrder.productCode}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">제품명</Label>
                  <div className="mt-1">{selectedWorkOrder.productName}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">규격</Label>
                  <div className="mt-1">{selectedWorkOrder.specification}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">단위</Label>
                  <div className="mt-1">{selectedWorkOrder.unit}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">목표 수량</Label>
                  <div className="mt-1 font-medium">{selectedWorkOrder.targetQuantity.toLocaleString()}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">완료 수량</Label>
                  <div className="mt-1 font-medium text-green-600">
                    {selectedWorkOrder.completedQuantity.toLocaleString()}
                  </div>
                </div>
                <div>
                  <Label className="text-muted-foreground">시작일</Label>
                  <div className="mt-1">{selectedWorkOrder.startDate}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">납기일</Label>
                  <div className="mt-1">{selectedWorkOrder.dueDate}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">작업자</Label>
                  <div className="mt-1">{selectedWorkOrder.worker}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">우선순위</Label>
                  <div className="mt-1">
                    {getPriorityBadge(selectedWorkOrder.priority)}
                  </div>
                </div>
              </div>

              <div>
                <Label className="text-muted-foreground">진행률</Label>
                <div className="mt-2">
                  <div className="flex items-center gap-3">
                    <div className="flex-1 bg-muted rounded-full h-4">
                      <div
                        className="bg-primary h-4 rounded-full transition-all"
                        style={{
                          width: `${selectedWorkOrder.targetQuantity > 0
                            ? (selectedWorkOrder.completedQuantity / selectedWorkOrder.targetQuantity * 100)
                            : 0}%`
                        }}
                      />
                    </div>
                    <span className="text-sm font-medium">
                      {selectedWorkOrder.targetQuantity > 0
                        ? ((selectedWorkOrder.completedQuantity / selectedWorkOrder.targetQuantity) * 100).toFixed(1)
                        : 0}%
                    </span>
                  </div>
                </div>
              </div>

              {selectedWorkOrder.note && (
                <div>
                  <Label className="text-muted-foreground">비고</Label>
                  <div className="mt-2 p-3 bg-muted rounded-lg">
                    {selectedWorkOrder.note}
                  </div>
                </div>
              )}
            </div>
          )}

          <div className="flex justify-end gap-2 mt-4">
            <Button variant="outline" onClick={() => setIsDetailDialogOpen(false)}>
              닫기
            </Button>
            <Button onClick={() => toast.info("작업지시서 출력 (개발 예정)")}>
              <FileText className="w-4 h-4 mr-2" />
              작업지시서 출력
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}
