import { useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Badge } from "./ui/badge";
import { Search, Package } from "lucide-react";
import { ItemMaster } from "./contexts/DataContext";

interface BOMItemSelectionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSelect: (item: ItemMaster) => void;
  itemMasters: ItemMaster[];
}

export function BOMItemSelectionDialog({ open, onOpenChange, onSelect, itemMasters }: BOMItemSelectionDialogProps) {
  const [selectedTab, setSelectedTab] = useState<string>("PT");
  const [searchQuery, setSearchQuery] = useState("");
  
  // 부품 분류 선택 상태
  const [partCategory, setPartCategory] = useState<string>("");
  
  // 가이드레일 동적 필드 상태
  const [installLocation, setInstallLocation] = useState<string>("");
  const [shape, setShape] = useState<string>("");
  const [length, setLength] = useState<string>("");
  
  // 모터 동적 필드 상태
  const [motorCapacity, setMotorCapacity] = useState<string>("");
  const [motorVoltage, setMotorVoltage] = useState<string>("");
  
  // 체인 동적 필드 상태
  const [chainSpec, setChainSpec] = useState<string>("");
  const [chainLength, setChainLength] = useState<string>("");
  
  // 부품 분류 옵션
  const partCategories = [
    { value: "guide_rail", label: "가이드레일" },
    { value: "motor", label: "모터" },
    { value: "chain", label: "체인" },
    { value: "bending", label: "절곡품" },
    { value: "etc", label: "기타" }
  ];
  
  // 필터링된 품목 목록
  const filteredItems = itemMasters.filter(item => {
    // 탭에 따른 필터링
    if (selectedTab === "PT" && item.itemType !== "PT") return false;
    if (selectedTab === "RM" && item.itemType !== "RM") return false;
    if (selectedTab === "SM" && item.itemType !== "SM") return false;
    
    // 검색어 필터링
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        item.itemCode?.toLowerCase().includes(query) ||
        item.itemName?.toLowerCase().includes(query) ||
        item.specification?.toLowerCase().includes(query)
      );
    }
    
    return true;
  });
  
  const handleDialogClose = () => {
    setSearchQuery("");
    setPartCategory("");
    setInstallLocation("");
    setShape("");
    setLength("");
    setMotorCapacity("");
    setMotorVoltage("");
    setChainSpec("");
    setChainLength("");
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleDialogClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>품목 검색</DialogTitle>
          <DialogDescription>
            검색하여 BOM에 추가할 품목을 찾으세요
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4">
          {/* 부품 분류 선택 */}
          <div>
            <Label>부품 분류 *</Label>
            <Select value={partCategory} onValueChange={setPartCategory}>
              <SelectTrigger>
                <SelectValue placeholder="부품 분류를 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                {partCategories.map((cat) => (
                  <SelectItem key={cat.value} value={cat.value}>
                    {cat.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground mt-1">
              * 부품 분류를 선택하면 관련 입력 항목이 표시됩니다
            </p>
          </div>
          
          {/* 가이드레일 선택 시 동적 필드 */}
          {partCategory === "guide_rail" && (
            <div className="grid grid-cols-3 gap-4 p-4 bg-blue-50 rounded-lg border border-blue-200">
              <div>
                <Label>설치 위치 *</Label>
                <Select value={installLocation} onValueChange={setInstallLocation}>
                  <SelectTrigger>
                    <SelectValue placeholder="설치 위치 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="wall">벽면</SelectItem>
                    <SelectItem value="side">측면</SelectItem>
                    <SelectItem value="ceiling">천장</SelectItem>
                    <SelectItem value="floor">바닥</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <Label>형상 *</Label>
                <Select value={shape} onValueChange={setShape}>
                  <SelectTrigger>
                    <SelectValue placeholder="형상 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="I">I형</SelectItem>
                    <SelectItem value="H">H형</SelectItem>
                    <SelectItem value="C">C형</SelectItem>
                    <SelectItem value="L">L형</SelectItem>
                    <SelectItem value="T">T형</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <Label>길이 (mm) *</Label>
                <Input
                  type="number"
                  value={length}
                  onChange={(e) => setLength(e.target.value)}
                  placeholder="예: 3000"
                />
              </div>
            </div>
          )}
          
          {/* 모터 선택 시 동적 필드 */}
          {partCategory === "motor" && (
            <div className="grid grid-cols-2 gap-4 p-4 bg-green-50 rounded-lg border border-green-200">
              <div>
                <Label>모터 용량 (kW) *</Label>
                <Input
                  type="number"
                  value={motorCapacity}
                  onChange={(e) => setMotorCapacity(e.target.value)}
                  placeholder="예: 1.5"
                  step="0.1"
                />
              </div>
              
              <div>
                <Label>전압 (V) *</Label>
                <Select value={motorVoltage} onValueChange={setMotorVoltage}>
                  <SelectTrigger>
                    <SelectValue placeholder="전압 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="220">220V</SelectItem>
                    <SelectItem value="380">380V</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}
          
          {/* 체인 선택 시 동적 필드 */}
          {partCategory === "chain" && (
            <div className="grid grid-cols-2 gap-4 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
              <div>
                <Label>체인 규격 *</Label>
                <Select value={chainSpec} onValueChange={setChainSpec}>
                  <SelectTrigger>
                    <SelectValue placeholder="규격 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="40">40</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                    <SelectItem value="60">60</SelectItem>
                    <SelectItem value="80">80</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <Label>길이 (링크 수) *</Label>
                <Input
                  type="number"
                  value={chainLength}
                  onChange={(e) => setChainLength(e.target.value)}
                  placeholder="예: 100"
                />
              </div>
            </div>
          )}
          
          {/* 절곡품 선택 시 안내 */}
          {partCategory === "bending" && (
            <div className="p-4 bg-purple-50 rounded-lg border border-purple-200">
              <p className="text-sm text-purple-900">
                절곡품은 아래 등록된 품목 목록에서 선택하거나, 품목 등록 화면에서 절곡 전개도를 업로드하여 등록할 수 있습니다.
              </p>
            </div>
          )}
          
          {/* 기타 선택 시 안내 */}
          {partCategory === "etc" && (
            <div className="p-4 bg-gray-50 rounded-lg border border-gray-200">
              <p className="text-sm text-gray-900">
                기타 부품은 아래 등록된 품목 목록에서 선택하세요.
              </p>
            </div>
          )}
          
          {/* 등록된 품목에서 선택 */}
          {partCategory && (
            <>
              <div className="border-t pt-4">
                <Label className="mb-2 block">등록된 품목에서 선택</Label>
                
                <Tabs value={selectedTab} onValueChange={setSelectedTab}>
                  <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="PT">부품</TabsTrigger>
                    <TabsTrigger value="RM">원자재</TabsTrigger>
                    <TabsTrigger value="SM">부자재</TabsTrigger>
                  </TabsList>
                  
                  <TabsContent value={selectedTab} className="space-y-4">
                    {/* 검색 */}
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="품목코드, 품목명, 규격으로 검색..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-10"
                      />
                    </div>
                    
                    {/* 품목 리스트 */}
                    <div className="border rounded-lg max-h-[300px] overflow-y-auto">
                      {filteredItems.length === 0 ? (
                        <div className="text-center py-8 text-muted-foreground">
                          <Package className="h-12 w-12 mx-auto mb-2 opacity-20" />
                          <p>등록된 품목이 없습니다</p>
                          <p className="text-xs mt-1">
                            {selectedTab === "PT" && "부품을 먼저 등록해주세요"}
                            {selectedTab === "RM" && "원자재를 먼저 등록해주세요"}
                            {selectedTab === "SM" && "부자재를 먼저 등록해주세요"}
                          </p>
                        </div>
                      ) : (
                        <div className="divide-y">
                          {filteredItems.map((item) => (
                            <div
                              key={item.id}
                              className="p-4 hover:bg-accent cursor-pointer transition-colors"
                              onClick={() => {
                                onSelect(item);
                                handleDialogClose();
                              }}
                            >
                              <div className="flex items-start justify-between">
                                <div className="flex-1">
                                  <div className="flex items-center gap-2 mb-1">
                                    <code className="text-xs bg-gray-100 px-2 py-0.5 rounded">
                                      {item.itemCode}
                                    </code>
                                    <span className="font-medium">{item.itemName}</span>
                                    {item.specification && (
                                      <span className="text-sm text-muted-foreground">
                                        ({item.specification})
                                      </span>
                                    )}
                                  </div>
                                  <div className="text-xs text-muted-foreground">
                                    {item.category1}
                                    {item.category2 && ` > ${item.category2}`}
                                    {item.category3 && ` > ${item.category3}`}
                                  </div>
                                </div>
                                <Badge variant="secondary">{item.unit}</Badge>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </TabsContent>
                </Tabs>
              </div>
            </>
          )}
        </div>
        
        <div className="flex justify-end gap-2 pt-4 border-t">
          <Button variant="outline" onClick={handleDialogClose}>
            취소
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
