import { useState } from "react";
import { ListPageTemplate } from './templates/ListPageTemplate';
import { Column } from "./organisms/DataTable";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "./ui/dialog";
import { StandardDialog } from "./molecules/StandardDialog";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Layers, Plus, Edit, Trash2, Copy, GitBranch, Eye } from "lucide-react";
import { Badge } from "./ui/badge";
import { Card, CardContent } from "./ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";

interface BOMLine {
  id: string;
  childItemCode: string;
  childItemName: string;
  quantity: number;
  unit: string;
}

interface BOM {
  id: string;
  parentItemCode: string;
  parentItemName: string;
  version: string;
  isActive: boolean;
  lines: BOMLine[];
  createdAt: string;
  updatedAt: string;
}

export function BOMManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [selectedBOM, setSelectedBOM] = useState<BOM | null>(null);

  // 샘플 BOM 데이터
  const [boms, setBOMs] = useState<BOM[]>([
    {
      id: "1",
      parentItemCode: "FG-001",
      parentItemName: "완제품 A",
      version: "1.0",
      isActive: true,
      lines: [
        { id: "l1", childItemCode: "RM-001", childItemName: "원자재 A", quantity: 2, unit: "kg" },
        { id: "l2", childItemCode: "RM-002", childItemName: "원자재 B", quantity: 1, unit: "개" }
      ],
      createdAt: "2025-01-15",
      updatedAt: "2025-01-15"
    },
    {
      id: "2",
      parentItemCode: "FG-002",
      parentItemName: "완제품 B",
      version: "1.0",
      isActive: true,
      lines: [
        { id: "l3", childItemCode: "RM-003", childItemName: "원자재 C", quantity: 3, unit: "m" },
        { id: "l4", childItemCode: "SM-001", childItemName: "반제품 A", quantity: 1, unit: "개" }
      ],
      createdAt: "2025-01-14",
      updatedAt: "2025-01-14"
    },
    {
      id: "3",
      parentItemCode: "SM-001",
      parentItemName: "반제품 A",
      version: "1.0",
      isActive: true,
      lines: [
        { id: "l5", childItemCode: "RM-004", childItemName: "원자재 D", quantity: 5, unit: "개" }
      ],
      createdAt: "2025-01-13",
      updatedAt: "2025-01-13"
    }
  ]);

  const filteredBOMs = boms.filter(bom =>
    bom.parentItemName.toLowerCase().includes(searchTerm.toLowerCase()) ||
    bom.parentItemCode.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const totalBOMs = boms.length;
  const activeBOMs = boms.filter(b => b.isActive).length;
  const fgBOMs = boms.filter(b => b.parentItemCode.startsWith("FG")).length;
  const smBOMs = boms.filter(b => b.parentItemCode.startsWith("SM")).length;

  const handleNew = () => {
    setSelectedBOM(null);
    setIsDialogOpen(true);
  };

  const handleEdit = (bom: BOM) => {
    setSelectedBOM(bom);
    setIsDialogOpen(true);
  };

  const handleView = (bom: BOM) => {
    setSelectedBOM(bom);
    setIsViewDialogOpen(true);
  };

  const handleCopy = (bom: BOM) => {
    const newBOM: BOM = {
      ...bom,
      id: String(boms.length + 1),
      version: "1.0",
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0]
    };
    setBOMs([...boms, newBOM]);
  };

  const handleDelete = (bom: BOM) => {
    if (confirm(`${bom.parentItemName} BOM을 삭제하시겠습니까?`)) {
      setBOMs(boms.filter(b => b.id !== bom.id));
    }
  };

  const columns: Column<BOM>[] = [
    { 
      key: "parentItemCode", 
      label: "품목코드"
    },
    { 
      key: "parentItemName", 
      label: "품목명"
    },
    { 
      key: "version", 
      label: "버전",
      render: (value) => <Badge variant="outline">{value as string}</Badge>
    },
    { 
      key: "isActive", 
      label: "상태",
      render: (value) => {
        const isActive = value as boolean;
        return <Badge variant={isActive ? "default" : "secondary"}>{isActive ? "활성" : "비활성"}</Badge>;
      }
    },
    { 
      key: "lines", 
      label: "구성품 수",
      render: (value) => `${(value as BOMLine[]).length}개`
    },
    { 
      key: "updatedAt", 
      label: "수정일"
    },
    {
      key: "actions",
      label: "관리",
      render: (_, row) => (
        <div className="flex justify-end gap-1">
          <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={() => handleView(row)}>
            <Eye className="h-4 w-4" />
          </Button>
          <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={() => handleEdit(row)}>
            <Edit className="h-4 w-4" />
          </Button>
          <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={() => handleCopy(row)}>
            <Copy className="h-4 w-4" />
          </Button>
          <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={() => handleDelete(row)}>
            <Trash2 className="h-4 w-4 text-red-500" />
          </Button>
        </div>
      )
    }
  ];

  return (
    <>
      <ListPageTemplate
        title="BOM 목록"
        description="자재 명세서(Bill of Materials)를 관리합니다"
        icon={Layers}
        stats={[
          {
            label: "전체 BOM",
            value: `${totalBOMs}개`,
            icon: Layers,
            iconColor: "text-blue-600",
            description: "등록된 BOM"
          },
          {
            label: "활성 BOM",
            value: `${activeBOMs}개`,
            icon: GitBranch,
            iconColor: "text-green-600",
            description: `${((activeBOMs / totalBOMs) * 100).toFixed(1)}%`
          },
          {
            label: "완제품",
            value: `${fgBOMs}개`,
            icon: Layers,
            iconColor: "text-purple-600",
            description: "FG 품목"
          },
          {
            label: "반제품",
            value: `${smBOMs}개`,
            icon: Layers,
            iconColor: "text-orange-600",
            description: "SM 품목"
          }
        ]}
        actions={
          <Button onClick={handleNew}>
            <Plus className="w-4 h-4 mr-2" />
            BOM 등록
          </Button>
        }
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="품목코드, 품목명으로 검색..."
        data={filteredBOMs}
        keyField="id"
        columns={columns}
        renderMobileCard={(bom) => ({
          title: bom.parentItemName,
          subtitle: `${bom.parentItemCode} | v${bom.version}`,
          badge: {
            label: bom.isActive ? "활성" : "비활성",
            variant: bom.isActive ? "default" : "secondary"
          },
          fields: [
            {
              label: "구성품 수",
              value: `${bom.lines.length}개`
            },
            {
              label: "수정일",
              value: bom.updatedAt
            }
          ],
          actions: [
            {
              label: "상세보기",
              icon: Eye,
              onClick: () => handleView(bom)
            },
            {
              label: "수정",
              icon: Edit,
              onClick: () => handleEdit(bom)
            },
            {
              label: "복사",
              icon: Copy,
              onClick: () => handleCopy(bom)
            },
            {
              label: "삭제",
              icon: Trash2,
              onClick: () => handleDelete(bom),
              variant: "destructive"
            }
          ]
        })}
        emptyIcon={Layers}
        emptyTitle="등록된 BOM이 없습니다"
        emptyDescription="새 BOM을 등록해주세요"
      />

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>BOM 상세 정보</DialogTitle>
            <DialogDescription>
              {selectedBOM?.parentItemName} ({selectedBOM?.parentItemCode})
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {selectedBOM && (
              <>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>버전</Label>
                    <p className="mt-1">{selectedBOM.version}</p>
                  </div>
                  <div>
                    <Label>상태</Label>
                    <p className="mt-1">
                      <Badge variant={selectedBOM.isActive ? "default" : "secondary"}>
                        {selectedBOM.isActive ? "활성" : "비활성"}
                      </Badge>
                    </p>
                  </div>
                  <div>
                    <Label>생성일</Label>
                    <p className="mt-1">{selectedBOM.createdAt}</p>
                  </div>
                  <div>
                    <Label>수정일</Label>
                    <p className="mt-1">{selectedBOM.updatedAt}</p>
                  </div>
                </div>
                
                <div>
                  <Label>구성품 목록</Label>
                  <Card className="mt-2">
                    <CardContent className="p-0">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>품목코드</TableHead>
                            <TableHead>품목명</TableHead>
                            <TableHead className="text-right">수량</TableHead>
                            <TableHead>단위</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {selectedBOM.lines.map((line) => (
                            <TableRow key={line.id}>
                              <TableCell>{line.childItemCode}</TableCell>
                              <TableCell>{line.childItemName}</TableCell>
                              <TableCell className="text-right">{line.quantity}</TableCell>
                              <TableCell>{line.unit}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                </div>
              </>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsViewDialogOpen(false)}>
              닫기
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit/Create Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {selectedBOM ? 'BOM 수정' : 'BOM 등록'}
            </DialogTitle>
            <DialogDescription>
              {selectedBOM ? 'BOM 정보를 수정합니다.' : '새로운 BOM을 등록합니다.'}
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <p className="text-sm text-muted-foreground">BOM 등록/수정 기능은 별도로 구현됩니다.</p>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}