import { useState } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Label } from "./ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "./ui/alert-dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "./ui/dialog";
import { Plus, Edit, Trash2, X } from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData, SpecificationMaster } from "./contexts/DataContext";

export function SpecificationManagement() {
  const { specificationMasters, addSpecificationMaster, updateSpecificationMaster, deleteSpecificationMaster } = useData();
  
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingSpec, setEditingSpec] = useState<SpecificationMaster | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [specToDelete, setSpecToDelete] = useState<SpecificationMaster | null>(null);
  
  const [formData, setFormData] = useState({
    itemType: "RM" as "RM" | "SM",
    fieldCount: "1" as "1" | "2" | "3",
    thickness: "",
    widthA: "",
    widthB: "",
    widthC: "",
    length: "",
    description: ""
  });

  const generateSpecCode = () => {
    const { thickness, widthA, widthB, widthC, length, fieldCount } = formData;
    if (!thickness || !widthA || !length) return "";
    
    if (fieldCount === "1") {
      return `${thickness} x ${widthA} x ${length}`;
    } else if (fieldCount === "2") {
      if (!widthB) return "";
      return `${thickness} x ${widthA} x ${widthB} x ${length}`;
    } else {
      if (!widthB || !widthC) return "";
      return `${thickness} x ${widthA} x ${widthB} x ${widthC} x ${length}`;
    }
  };

  const handleOpenDialog = (spec?: SpecificationMaster) => {
    if (spec) {
      setEditingSpec(spec);
      setFormData({
        itemType: spec.itemType,
        fieldCount: spec.fieldCount,
        thickness: spec.thickness,
        widthA: spec.widthA,
        widthB: spec.widthB || "",
        widthC: spec.widthC || "",
        length: spec.length,
        description: spec.description || ""
      });
    } else {
      setEditingSpec(null);
      setFormData({
        itemType: "RM",
        fieldCount: "1",
        thickness: "",
        widthA: "",
        widthB: "",
        widthC: "",
        length: "",
        description: ""
      });
    }
    setIsDialogOpen(true);
  };

  const handleSave = () => {
    const specCode = generateSpecCode();
    if (!specCode) {
      toast.error("필수 항목을 모두 입력해주세요.");
      return;
    }

    if (editingSpec) {
      // 수정
      updateSpecificationMaster(editingSpec.id, {
        itemType: formData.itemType,
        fieldCount: formData.fieldCount,
        specificationCode: specCode,
        thickness: formData.thickness,
        widthA: formData.widthA,
        widthB: formData.widthB || undefined,
        widthC: formData.widthC || undefined,
        length: formData.length,
        description: formData.description || undefined,
        updatedAt: new Date().toISOString()
      });
      toast.success("규격이 수정되었습니다.");
    } else {
      // 추가
      const newSpec: SpecificationMaster = {
        id: `SPEC-${Date.now()}`,
        itemType: formData.itemType,
        fieldCount: formData.fieldCount,
        specificationCode: specCode,
        thickness: formData.thickness,
        widthA: formData.widthA,
        widthB: formData.widthB || undefined,
        widthC: formData.widthC || undefined,
        length: formData.length,
        description: formData.description || undefined,
        isActive: true,
        createdAt: new Date().toISOString()
      };
      addSpecificationMaster(newSpec);
      toast.success("규격이 추가되었습니다.");
    }
    
    setIsDialogOpen(false);
  };

  const handleDelete = () => {
    if (specToDelete) {
      deleteSpecificationMaster(specToDelete.id);
      toast.success("규격이 삭제되었습니다.");
      setIsDeleteDialogOpen(false);
      setSpecToDelete(null);
    }
  };

  const filteredSpecs = specificationMasters.filter(spec => spec.isActive);

  return (
    <>
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>규격 목록 관리</CardTitle>
          <Button onClick={() => handleOpenDialog()}>
            <Plus className="h-4 w-4 mr-2" />
            규격 추가
          </Button>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>품목유형</TableHead>
                <TableHead>규격 코드</TableHead>
                <TableHead>두께</TableHead>
                <TableHead>너비</TableHead>
                <TableHead>길이</TableHead>
                <TableHead>설명</TableHead>
                <TableHead className="text-right">작업</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredSpecs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground">
                    등록된 규격이 없습니다.
                  </TableCell>
                </TableRow>
              ) : (
                filteredSpecs.map((spec) => (
                  <TableRow key={spec.id}>
                    <TableCell>{spec.itemType === "RM" ? "원자재" : "부자재"}</TableCell>
                    <TableCell>{spec.specificationCode}</TableCell>
                    <TableCell>{spec.thickness}</TableCell>
                    <TableCell>
                      {spec.fieldCount === "1" && spec.widthA}
                      {spec.fieldCount === "2" && `${spec.widthA} / ${spec.widthB}`}
                      {spec.fieldCount === "3" && `${spec.widthA} / ${spec.widthB} / ${spec.widthC}`}
                    </TableCell>
                    <TableCell>{spec.length}</TableCell>
                    <TableCell>{spec.description || "-"}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleOpenDialog(spec)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSpecToDelete(spec);
                            setIsDeleteDialogOpen(true);
                          }}
                        >
                          <Trash2 className="h-4 w-4 text-red-600" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 규격 추가/수정 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingSpec ? "규격 수정" : "규격 추가"}</DialogTitle>
            <DialogDescription>
              규격 정보를 입력하세요.
            </DialogDescription>
          </DialogHeader>
          
          <div className="grid gap-4 py-4">
            {/* 품목유형 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">품목유형</Label>
              <div className="col-span-3">
                <Select
                  value={formData.itemType}
                  onValueChange={(value: "RM" | "SM") => setFormData({ ...formData, itemType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="RM">원자재</SelectItem>
                    <SelectItem value="SM">부자재</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 규격 입력 방식 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">규격 입력 방식</Label>
              <div className="col-span-3">
                <Select
                  value={formData.fieldCount}
                  onValueChange={(value: "1" | "2" | "3") => setFormData({ ...formData, fieldCount: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1">두께 x 너비 x 길이</SelectItem>
                    <SelectItem value="2">두께 x 너비A x 너비B x 길이</SelectItem>
                    <SelectItem value="3">두께 x 너비A x 너비B x 너비C x 길이</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 두께 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">두께</Label>
              <div className="col-span-3">
                <Input
                  value={formData.thickness}
                  onChange={(e) => setFormData({ ...formData, thickness: e.target.value })}
                  placeholder="예: 1.6T"
                />
              </div>
            </div>

            {/* 너비A */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">
                {formData.fieldCount === "1" ? "너비" : "너비A"}
              </Label>
              <div className="col-span-3">
                <Input
                  value={formData.widthA}
                  onChange={(e) => setFormData({ ...formData, widthA: e.target.value })}
                  placeholder="예: 1219"
                />
              </div>
            </div>

            {/* 너비B */}
            {(formData.fieldCount === "2" || formData.fieldCount === "3") && (
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">너비B</Label>
                <div className="col-span-3">
                  <Input
                    value={formData.widthB}
                    onChange={(e) => setFormData({ ...formData, widthB: e.target.value })}
                    placeholder="예: 45"
                  />
                </div>
              </div>
            )}

            {/* 너비C */}
            {formData.fieldCount === "3" && (
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">너비C</Label>
                <div className="col-span-3">
                  <Input
                    value={formData.widthC}
                    onChange={(e) => setFormData({ ...formData, widthC: e.target.value })}
                    placeholder="예: 123"
                  />
                </div>
              </div>
            )}

            {/* 길이 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">길이</Label>
              <div className="col-span-3">
                <Input
                  value={formData.length}
                  onChange={(e) => setFormData({ ...formData, length: e.target.value })}
                  placeholder="예: 2438"
                />
              </div>
            </div>

            {/* 설명 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">설명</Label>
              <div className="col-span-3">
                <Input
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="선택사항"
                />
              </div>
            </div>

            {/* 미리보기 */}
            {generateSpecCode() && (
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">규격 미리보기</Label>
                <div className="col-span-3">
                  <div className="bg-muted p-2 rounded">
                    {generateSpecCode()}
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
              취소
            </Button>
            <Button onClick={handleSave}>
              저장
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>규격 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              "{specToDelete?.specificationCode}" 규격을 삭제하시겠습니까?
              <br />
              이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}