import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { RadioGroup, RadioGroupItem } from "./ui/radio-group";
import { Checkbox } from "./ui/checkbox";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { 
  Plus,
  Copy,
  Trash2,
  Save,
  ArrowLeft,
  Search,
  Calendar
} from "lucide-react";
import { toast } from "sonner@2.0.3";

// 재질별 목록 항목
interface MaterialItem {
  id: string;
  material: string;
  materialName: string;
  quantity: number;
}

// 부품 조회 항목
interface PartItem {
  id: string;
  no: number;
  material: string;
  partCode: string;
  partName: string;
  specification: string;
  quantity: number;
  unit: string;
  unitPrice: number;
  totalAmount: number;
  note: string;
}

interface BOMRegistrationProps {
  onBack?: () => void;
}

export function BOMRegistration({ onBack }: BOMRegistrationProps = {}) {
  // 기본 정보
  const [registrationDate, setRegistrationDate] = useState("2025-10-22");
  const [author, setAuthor] = useState("생성자");
  const [title, setTitle] = useState("");
  
  // 리비전 번호
  const [isFirstRevision, setIsFirstRevision] = useState(false);
  const [isSecondRevision, setIsSecondRevision] = useState(false);
  
  // 테필터 (라디오 버튼)
  const [filterType, setFilterType] = useState("small");
  
  // 선택 필드
  const [industry, setIndustry] = useState("");
  const [department, setDepartment] = useState("");
  const [equipmentCode, setEquipmentCode] = useState("");
  
  // 재질별 목록
  const [materialItems, setMaterialItems] = useState<MaterialItem[]>([
    { id: "1", material: "EXC", materialName: "일반강판", quantity: 738 },
    { id: "2", material: "SUS", materialName: "스테인리스", quantity: 132 },
    { id: "3", material: "L2T", materialName: "알루미늄", quantity: 0 },
  ]);
  
  // 부품 목록
  const [partItems, setPartItems] = useState<PartItem[]>([
    {
      id: "1",
      no: 1,
      material: "43",
      partCode: "PT-001",
      partName: "가이드 레일",
      specification: "50x30x2000",
      quantity: 105,
      unit: "EA",
      unitPrice: 43,
      totalAmount: 4515,
      note: ""
    },
    {
      id: "2",
      no: 2,
      material: "43",
      partCode: "PT-002",
      partName: "브라켓",
      specification: "100x50",
      quantity: 147,
      unit: "EA",
      unitPrice: 190,
      totalAmount: 27930,
      note: ""
    },
    {
      id: "3",
      no: 3,
      material: "43",
      partCode: "PT-003",
      partName: "연결판",
      specification: "80x40",
      quantity: 104,
      unit: "EA",
      unitPrice: 63,
      totalAmount: 6552,
      note: ""
    },
  ]);

  // 부품 추가
  const addPart = () => {
    const newPart: PartItem = {
      id: Date.now().toString(),
      no: partItems.length + 1,
      material: "",
      partCode: "",
      partName: "",
      specification: "",
      quantity: 1,
      unit: "EA",
      unitPrice: 0,
      totalAmount: 0,
      note: ""
    };
    setPartItems([...partItems, newPart]);
    toast.success("부품이 추가되었습니다.");
  };

  // 부품 복사
  const copyPart = (id: string) => {
    const partToCopy = partItems.find(p => p.id === id);
    if (partToCopy) {
      const newPart: PartItem = {
        ...partToCopy,
        id: Date.now().toString(),
        no: partItems.length + 1
      };
      setPartItems([...partItems, newPart]);
      toast.success("부품이 복사되었습니다.");
    }
  };

  // 부품 삭제
  const removePart = (id: string) => {
    const newPartItems = partItems.filter(p => p.id !== id);
    // 번호 재정렬
    const reorderedItems = newPartItems.map((p, idx) => ({ ...p, no: idx + 1 }));
    setPartItems(reorderedItems);
    toast.info("부품이 삭제되었습니다.");
  };

  // 부품 정보 업데이트
  const updatePart = (id: string, field: keyof PartItem, value: any) => {
    setPartItems(partItems.map(p => {
      if (p.id === id) {
        const updated = { ...p, [field]: value };
        // 수량 또는 단가 변경 시 금액 자동 계산
        if (field === "quantity" || field === "unitPrice") {
          updated.totalAmount = updated.quantity * updated.unitPrice;
        }
        return updated;
      }
      return p;
    }));
  };

  // 재질 추가
  const addMaterial = () => {
    const newMaterial: MaterialItem = {
      id: Date.now().toString(),
      material: "",
      materialName: "",
      quantity: 0
    };
    setMaterialItems([...materialItems, newMaterial]);
    toast.success("재질이 추가되었습니다.");
  };

  // 재질 삭제
  const removeMaterial = (id: string) => {
    if (materialItems.length <= 1) {
      toast.error("최소 1개의 재질은 필요합니다.");
      return;
    }
    setMaterialItems(materialItems.filter(m => m.id !== id));
    toast.info("재질이 삭제되었습니다.");
  };

  // 재질 정보 업데이트
  const updateMaterial = (id: string, field: keyof MaterialItem, value: any) => {
    setMaterialItems(materialItems.map(m => 
      m.id === id ? { ...m, [field]: value } : m
    ));
  };

  // 장비 검색
  const searchEquipment = () => {
    toast.info("장비를 검색합니다...");
  };

  // 저장
  const handleSave = () => {
    if (!title) {
      toast.error("제목을 입력해주세요.");
      return;
    }

    const bomData = {
      registrationDate,
      author,
      title,
      isFirstRevision,
      isSecondRevision,
      filterType,
      industry,
      department,
      equipmentCode,
      materialItems,
      partItems
    };

    console.log("BOM 등록 데이터:", bomData);
    toast.success("BOM이 등록되었습니다.");
    
    if (onBack) {
      onBack();
    }
  };

  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Button variant="outline" size="sm" onClick={onBack}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            목록으로
          </Button>
          <div>
            <h1 className="text-2xl">BOM 등록</h1>
            <p className="text-sm text-muted-foreground mt-1">
              새로운 BOM을 등록합니다.
            </p>
          </div>
        </div>
        <Button onClick={handleSave} size="lg">
          <Save className="w-4 h-4 mr-2" />
          등록
        </Button>
      </div>

      {/* 기본 정보 카드 */}
      <Card>
        <CardContent className="pt-6 space-y-4">
          {/* 첫 번째 행: 등록일, 작성자, 제목 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label>등록일</Label>
              <div className="relative mt-2">
                <Input
                  type="date"
                  value={registrationDate}
                  onChange={(e) => setRegistrationDate(e.target.value)}
                />
                <Calendar className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
              </div>
            </div>
            <div>
              <Label>작성자</Label>
              <Input
                value={author}
                onChange={(e) => setAuthor(e.target.value)}
                className="mt-2"
              />
            </div>
            <div>
              <Label>제목 *</Label>
              <Input
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="제목을 입력하세요"
                className="mt-2"
              />
            </div>
          </div>

          {/* 두 번째 행: 리비전 번호 */}
          <div>
            <Label>리비전 번호</Label>
            <div className="flex flex-wrap gap-6 mt-2">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="first-revision"
                  checked={isFirstRevision}
                  onCheckedChange={(checked) => setIsFirstRevision(checked as boolean)}
                />
                <Label htmlFor="first-revision" className="cursor-pointer">
                  가번(1차)
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="second-revision"
                  checked={isSecondRevision}
                  onCheckedChange={(checked) => setIsSecondRevision(checked as boolean)}
                />
                <Label htmlFor="second-revision" className="cursor-pointer">
                  세번(2차)
                </Label>
              </div>
            </div>
          </div>

          {/* 세 번째 행: 테필터 라디오 버튼 */}
          <div>
            <Label>테필터</Label>
            <RadioGroup value={filterType} onValueChange={setFilterType} className="mt-2">
              <div className="flex flex-wrap gap-6">
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="small" id="small" />
                  <Label htmlFor="small" className="cursor-pointer">소규모</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="mass" id="mass" />
                  <Label htmlFor="mass" className="cursor-pointer">양산</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="module" id="module" />
                  <Label htmlFor="module" className="cursor-pointer">모듈명령</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="manufacture" id="manufacture" />
                  <Label htmlFor="manufacture" className="cursor-pointer">제조가</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="legal" id="legal" />
                  <Label htmlFor="legal" className="cursor-pointer">법무팀</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="change" id="change" />
                  <Label htmlFor="change" className="cursor-pointer">변경</Label>
                </div>
              </div>
            </RadioGroup>
          </div>

          {/* 네 번째 행: 산업, 마당, 출장장비 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label>산업</Label>
              <Select value={industry} onValueChange={setIndustry}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="#0501">#0501</SelectItem>
                  <SelectItem value="#0502">#0502</SelectItem>
                  <SelectItem value="#0503">#0503</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>마당</Label>
              <Select value={department} onValueChange={setDepartment}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="민명룡">민명룡</SelectItem>
                  <SelectItem value="김철수">김철수</SelectItem>
                  <SelectItem value="이영희">이영희</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>출장장비</Label>
              <div className="flex gap-2 mt-2">
                <Input
                  value={equipmentCode}
                  onChange={(e) => setEquipmentCode(e.target.value)}
                  placeholder="조립부행번호"
                />
                <Button onClick={searchEquipment} size="icon">
                  <Search className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 재정별 목록 */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>재정별 목록</CardTitle>
          <div className="flex gap-2">
            <Button onClick={addMaterial} size="sm" variant="outline">
              <Plus className="w-4 h-4 mr-2" />
              재질 추가
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* 데스크톱 테이블 */}
          <div className="hidden md:block overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-32">재질</TableHead>
                  <TableHead>재질명</TableHead>
                  <TableHead className="w-32 text-right">수량</TableHead>
                  <TableHead className="w-20 text-center">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {materialItems.map((material) => (
                  <TableRow key={material.id}>
                    <TableCell>
                      <Input
                        value={material.material}
                        onChange={(e) => updateMaterial(material.id, "material", e.target.value)}
                        placeholder="재질"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={material.materialName}
                        onChange={(e) => updateMaterial(material.id, "materialName", e.target.value)}
                        placeholder="재질명"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        type="number"
                        value={material.quantity}
                        onChange={(e) => updateMaterial(material.id, "quantity", parseFloat(e.target.value) || 0)}
                        className="text-right"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="flex justify-center">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => removeMaterial(material.id)}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 모바일 카드 */}
          <div className="md:hidden space-y-4">
            {materialItems.map((material) => (
              <Card key={material.id}>
                <CardContent className="pt-6 space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm">재질 정보</span>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeMaterial(material.id)}
                    >
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </Button>
                  </div>
                  <div>
                    <Label>재질</Label>
                    <Input
                      value={material.material}
                      onChange={(e) => updateMaterial(material.id, "material", e.target.value)}
                      placeholder="재질"
                      className="mt-1"
                    />
                  </div>
                  <div>
                    <Label>재질명</Label>
                    <Input
                      value={material.materialName}
                      onChange={(e) => updateMaterial(material.id, "materialName", e.target.value)}
                      placeholder="재질명"
                      className="mt-1"
                    />
                  </div>
                  <div>
                    <Label>수량</Label>
                    <Input
                      type="number"
                      value={material.quantity}
                      onChange={(e) => updateMaterial(material.id, "quantity", parseFloat(e.target.value) || 0)}
                      className="mt-1"
                    />
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 원고 무장 조회 (정보 부품 조회) */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>원고 무장 조회</CardTitle>
          <div className="flex gap-2">
            <Button onClick={addPart} size="sm">
              <Plus className="w-4 h-4 mr-2" />
              조사 추가
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* 데스크톱 테이블 */}
          <div className="hidden md:block overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">No</TableHead>
                  <TableHead className="w-20">면적</TableHead>
                  <TableHead>명칭</TableHead>
                  <TableHead>면제</TableHead>
                  <TableHead className="w-20">단가</TableHead>
                  <TableHead className="w-20">수량</TableHead>
                  <TableHead>금형</TableHead>
                  <TableHead className="w-20">단위</TableHead>
                  <TableHead>금액</TableHead>
                  <TableHead>기타</TableHead>
                  <TableHead className="w-24 text-center">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {partItems.map((part) => (
                  <TableRow key={part.id}>
                    <TableCell>{part.no}</TableCell>
                    <TableCell>
                      <Input
                        value={part.material}
                        onChange={(e) => updatePart(part.id, "material", e.target.value)}
                        className="w-20"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={part.partName}
                        onChange={(e) => updatePart(part.id, "partName", e.target.value)}
                        placeholder="명칭"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={part.specification}
                        onChange={(e) => updatePart(part.id, "specification", e.target.value)}
                        placeholder="면제"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        type="number"
                        value={part.unitPrice}
                        onChange={(e) => updatePart(part.id, "unitPrice", parseFloat(e.target.value) || 0)}
                        className="w-20"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        type="number"
                        value={part.quantity}
                        onChange={(e) => updatePart(part.id, "quantity", parseFloat(e.target.value) || 0)}
                        className="w-20"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={part.partCode}
                        onChange={(e) => updatePart(part.id, "partCode", e.target.value)}
                        placeholder="금형"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={part.unit}
                        onChange={(e) => updatePart(part.id, "unit", e.target.value)}
                        className="w-20"
                      />
                    </TableCell>
                    <TableCell className="text-right">
                      {part.totalAmount.toLocaleString()}
                    </TableCell>
                    <TableCell>
                      <Input
                        value={part.note}
                        onChange={(e) => updatePart(part.id, "note", e.target.value)}
                        placeholder="기타"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-1 justify-center">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => copyPart(part.id)}
                        >
                          <Copy className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => removePart(part.id)}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 모바일 카드 */}
          <div className="md:hidden space-y-4">
            {partItems.map((part) => (
              <Card key={part.id}>
                <CardContent className="pt-6 space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm">No. {part.no}</span>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => copyPart(part.id)}
                      >
                        <Copy className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => removePart(part.id)}
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </Button>
                    </div>
                  </div>
                  
                  <div>
                    <Label>면적</Label>
                    <Input
                      value={part.material}
                      onChange={(e) => updatePart(part.id, "material", e.target.value)}
                      className="mt-1"
                    />
                  </div>
                  
                  <div>
                    <Label>명칭</Label>
                    <Input
                      value={part.partName}
                      onChange={(e) => updatePart(part.id, "partName", e.target.value)}
                      placeholder="명칭"
                      className="mt-1"
                    />
                  </div>
                  
                  <div>
                    <Label>면제</Label>
                    <Input
                      value={part.specification}
                      onChange={(e) => updatePart(part.id, "specification", e.target.value)}
                      placeholder="면제"
                      className="mt-1"
                    />
                  </div>
                  
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <Label>단가</Label>
                      <Input
                        type="number"
                        value={part.unitPrice}
                        onChange={(e) => updatePart(part.id, "unitPrice", parseFloat(e.target.value) || 0)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <Label>수량</Label>
                      <Input
                        type="number"
                        value={part.quantity}
                        onChange={(e) => updatePart(part.id, "quantity", parseFloat(e.target.value) || 0)}
                        className="mt-1"
                      />
                    </div>
                  </div>
                  
                  <div>
                    <Label>금형</Label>
                    <Input
                      value={part.partCode}
                      onChange={(e) => updatePart(part.id, "partCode", e.target.value)}
                      placeholder="금형"
                      className="mt-1"
                    />
                  </div>
                  
                  <div>
                    <Label>단위</Label>
                    <Input
                      value={part.unit}
                      onChange={(e) => updatePart(part.id, "unit", e.target.value)}
                      className="mt-1"
                    />
                  </div>
                  
                  <div>
                    <Label>금액</Label>
                    <div className="mt-1 p-2 bg-muted rounded text-right">
                      {part.totalAmount.toLocaleString()} 원
                    </div>
                  </div>
                  
                  <div>
                    <Label>기타</Label>
                    <Input
                      value={part.note}
                      onChange={(e) => updatePart(part.id, "note", e.target.value)}
                      placeholder="기타"
                      className="mt-1"
                    />
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* 합계 */}
          <div className="mt-4 p-4 bg-muted rounded-lg">
            <div className="flex justify-between items-center">
              <span>총 부품 수:</span>
              <span>{partItems.length}개</span>
            </div>
            <div className="flex justify-between items-center mt-2">
              <span>총 금액:</span>
              <span className="text-lg">
                {partItems.reduce((sum, item) => sum + item.totalAmount, 0).toLocaleString()} 원
              </span>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
