/**
 * 품질관리 - 디자인시스템 표준 패턴 적용
 * 
 * 표준 구조:
 * - 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, CardHeader, CardTitle } from "./ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
import {
  ClipboardCheck,
  CheckCircle,
  XCircle,
  Clock,
  Plus,
  Download,
  FileText,
  AlertTriangle,
  Package,
  Eye,
} from "lucide-react";
import { toast } from "sonner@2.0.3";

interface QualityInspection {
  id: string;
  inspectionNumber: string;
  inspectionType: "수입검사" | "중간검사" | "제품검사";
  lotNumber: string;
  itemCode: string;
  itemName: string;
  specification: string;
  quantity: number;
  unit: string;
  supplier: string;
  inspectionDate: string;
  inspector: string;
  result: "합격" | "불합격" | "조건부합격" | "검사중";
  defectType?: string;
  defectQuantity?: number;
  note?: string;
}

interface QualityManagementProps {
  defaultTab?: "incoming" | "process" | "final";
}

export function QualityManagement({ defaultTab = "incoming" }: QualityManagementProps = {}) {
  const [activeTab, setActiveTab] = useState<"incoming" | "process" | "final">(defaultTab);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterResult, setFilterResult] = useState<string>("all");
  const [isInspectionDialogOpen, setIsInspectionDialogOpen] = useState(false);
  const [selectedInspection, setSelectedInspection] = useState<QualityInspection | null>(null);

  // Mock 데이터
  const inspections: QualityInspection[] = [
    {
      id: "1",
      inspectionNumber: "IQC-250118-001",
      inspectionType: "수입검사",
      lotNumber: "250723-04",
      itemCode: "EGIT-SST",
      itemName: "EGIT-SST 강판",
      specification: "1219*3500",
      quantity: 80,
      unit: "예",
      supplier: "지프하스",
      inspectionDate: "2025-01-18",
      inspector: "김검사",
      result: "합격",
    },
    {
      id: "2",
      inspectionNumber: "IQC-250118-002",
      inspectionType: "수입검사",
      lotNumber: "250716-01",
      itemCode: "KSS-01",
      itemName: "용강코일",
      specification: "EGIT-SST(W)350",
      quantity: 9,
      unit: "롤",
      supplier: "지프하스",
      inspectionDate: "2025-01-18",
      inspector: "김검사",
      result: "검사중",
    },
    {
      id: "3",
      inspectionNumber: "PQC-250118-001",
      inspectionType: "중간검사",
      lotNumber: "WO-250118-01",
      itemCode: "SCR-001",
      itemName: "스크린 프레임",
      specification: "1200*2000",
      quantity: 50,
      unit: "EA",
      supplier: "자체생산",
      inspectionDate: "2025-01-18",
      inspector: "박검사",
      result: "합격",
    },
    {
      id: "4",
      inspectionNumber: "PQC-250118-002",
      inspectionType: "중간검사",
      lotNumber: "WO-250118-02",
      itemCode: "SLT-001",
      itemName: "슬랫",
      specification: "80mm",
      quantity: 100,
      unit: "EA",
      supplier: "자체생산",
      inspectionDate: "2025-01-18",
      inspector: "박검사",
      result: "불합격",
      defectType: "치수불량",
      defectQuantity: 3,
      note: "재작업 필요"
    },
    {
      id: "5",
      inspectionNumber: "FQC-250118-001",
      inspectionType: "제품검사",
      lotNumber: "FG-250118-01",
      itemCode: "PROD-001",
      itemName: "완제품 A",
      specification: "표준형",
      quantity: 10,
      unit: "SET",
      supplier: "자체생산",
      inspectionDate: "2025-01-18",
      inspector: "최검사",
      result: "합격",
    },
  ];

  // 통계 계산
  const stats = useMemo(() => {
    const filteredByTab = inspections.filter(i => {
      if (activeTab === "incoming") return i.inspectionType === "수입검사";
      if (activeTab === "process") return i.inspectionType === "중간검사";
      if (activeTab === "final") return i.inspectionType === "제품검사";
      return true;
    });

    return [
      {
        label: "총 검사",
        value: filteredByTab.length,
        icon: ClipboardCheck,
        iconColor: "text-blue-600"
      },
      {
        label: "합격",
        value: filteredByTab.filter(i => i.result === "합격").length,
        icon: CheckCircle,
        iconColor: "text-green-600"
      },
      {
        label: "불합격",
        value: filteredByTab.filter(i => i.result === "불합격").length,
        icon: XCircle,
        iconColor: "text-red-600"
      },
      {
        label: "검사중",
        value: filteredByTab.filter(i => i.result === "검사중").length,
        icon: Clock,
        iconColor: "text-orange-600"
      }
    ];
  }, [inspections, activeTab]);

  // 테이블 컬럼
  const columns: Column<QualityInspection>[] = [
    {
      key: "inspectionNumber",
      label: "검사번호",
      render: (item) => (
        <span className="font-mono text-sm">{item.inspectionNumber}</span>
      )
    },
    {
      key: "lotNumber",
      label: "LOT번호",
      render: (item) => (
        <span className="font-mono text-sm">{item.lotNumber}</span>
      )
    },
    {
      key: "itemName",
      label: "품목",
      render: (item) => (
        <div>
          <div className="font-medium">{item.itemName}</div>
          <div className="text-xs text-muted-foreground">{item.itemCode}</div>
        </div>
      )
    },
    {
      key: "specification",
      label: "규격",
    },
    {
      key: "quantity",
      label: "수량",
      render: (item) => (
        <span>{item.quantity} {item.unit}</span>
      )
    },
    {
      key: "supplier",
      label: "공급처",
    },
    {
      key: "inspectionDate",
      label: "검사일",
    },
    {
      key: "inspector",
      label: "검사자",
    },
    {
      key: "result",
      label: "결과",
      render: (item) => getResultBadge(item.result)
    },
  ];

  // 필터링
  const filteredInspections = useMemo(() => {
    return inspections.filter(item => {
      // 탭 필터
      const matchesTab = 
        (activeTab === "incoming" && item.inspectionType === "수입검사") ||
        (activeTab === "process" && item.inspectionType === "중간검사") ||
        (activeTab === "final" && item.inspectionType === "제품검사");

      // 검색 필터
      const matchesSearch = searchTerm === "" ||
        item.inspectionNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.lotNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.itemName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.itemCode.toLowerCase().includes(searchTerm.toLowerCase());

      // 결과 필터
      const matchesResult = filterResult === "all" || item.result === filterResult;

      return matchesTab && matchesSearch && matchesResult;
    });
  }, [inspections, activeTab, searchTerm, filterResult]);

  // 결과 뱃지
  const getResultBadge = (result: string) => {
    const variants: { [key: string]: { variant: any; className: string } } = {
      '합격': { variant: "outline", className: "bg-green-50 text-green-700 border-green-200" },
      '불합격': { variant: "outline", className: "bg-red-50 text-red-700 border-red-200" },
      '조건부합격': { variant: "outline", className: "bg-yellow-50 text-yellow-700 border-yellow-200" },
      '검사중': { variant: "outline", className: "bg-blue-50 text-blue-700 border-blue-200" },
    };
    const config = variants[result] || variants['검사중'];
    return <Badge variant={config.variant} className={config.className}>{result}</Badge>;
  };

  const handleView = (inspection: QualityInspection) => {
    setSelectedInspection(inspection);
    setIsInspectionDialogOpen(true);
  };

  const handleNewInspection = () => {
    toast.info("검사 등록 기능 (개발 예정)");
  };

  return (
    <PageLayout>
      <PageHeader
        title="품질관리"
        description="제품 검사 현황 및 품질 관리"
        icon={ClipboardCheck}
        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={handleNewInspection}>
              <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-3">
              <TabsTrigger value="incoming">수입검사</TabsTrigger>
              <TabsTrigger value="process">중간검사</TabsTrigger>
              <TabsTrigger value="final">제품검사</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="검사번호, LOT번호, 품목명으로 검색..."
                  />
                </div>
                <div className="w-full md:w-48">
                  <Select value={filterResult} onValueChange={setFilterResult}>
                    <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>

              {/* 검사 목록 */}
              {filteredInspections.length === 0 ? (
                <EmptyState
                  icon={ClipboardCheck}
                  title="검사 기록이 없습니다"
                  description="새로운 검사를 등록해보세요"
                  action={{
                    label: "검사 등록",
                    onClick: handleNewInspection
                  }}
                />
              ) : (
                <DataTable
                  columns={columns}
                  data={filteredInspections}
                  keyField="id"
                  onRowClick={handleView}
                />
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* 상세보기 다이얼로그 */}
      <Dialog open={isInspectionDialogOpen} onOpenChange={setIsInspectionDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>검사 상세 정보</DialogTitle>
            <DialogDescription>
              검사번호: {selectedInspection?.inspectionNumber}
            </DialogDescription>
          </DialogHeader>

          {selectedInspection && (
            <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>{selectedInspection.inspectionType}</Badge>
                  </div>
                </div>
                <div>
                  <Label className="text-muted-foreground">검사 결과</Label>
                  <div className="mt-1">
                    {getResultBadge(selectedInspection.result)}
                  </div>
                </div>
                <div>
                  <Label className="text-muted-foreground">LOT 번호</Label>
                  <div className="mt-1 font-mono">{selectedInspection.lotNumber}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">품목코드</Label>
                  <div className="mt-1 font-mono">{selectedInspection.itemCode}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">품목명</Label>
                  <div className="mt-1">{selectedInspection.itemName}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">규격</Label>
                  <div className="mt-1">{selectedInspection.specification}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">수량</Label>
                  <div className="mt-1">{selectedInspection.quantity} {selectedInspection.unit}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">공급처</Label>
                  <div className="mt-1">{selectedInspection.supplier}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">검사일</Label>
                  <div className="mt-1">{selectedInspection.inspectionDate}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">검사자</Label>
                  <div className="mt-1">{selectedInspection.inspector}</div>
                </div>
              </div>

              {selectedInspection.result === "불합격" && (
                <>
                  <div className="border-t pt-4">
                    <Label className="text-muted-foreground">불량 유형</Label>
                    <div className="mt-1 text-red-600">{selectedInspection.defectType}</div>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">불량 수량</Label>
                    <div className="mt-1 text-red-600">{selectedInspection.defectQuantity} {selectedInspection.unit}</div>
                  </div>
                </>
              )}

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

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