import React 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 { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
import { Badge } from "./ui/badge";
import { Package, Plus, Trash2, Check, ChevronsUpDown } from "lucide-react";
import { MultiConditionInput } from "./MultiConditionInput";
import type { RangeRule, RangeRuleItem, ItemMaster } from "./contexts/DataContext";

interface RangeRuleCardProps {
  range: RangeRule;
  index: number;
  isStage1: boolean;
  stage1ResultType?: string;
  itemMasters: ItemMaster[];
  onUpdateRange: (index: number, field: string, value: any) => void;
  onDeleteRange: (index: number) => void;
  onAddItem: (rangeIndex: number) => void;
  onUpdateItem: (rangeIndex: number, itemIndex: number, field: string, value: any) => void;
  onDeleteItem: (rangeIndex: number, itemIndex: number) => void;
}

export function RangeRuleCard({
  range,
  index,
  isStage1,
  stage1ResultType,
  itemMasters,
  onUpdateRange,
  onDeleteRange,
  onAddItem,
  onUpdateItem,
  onDeleteItem,
}: RangeRuleCardProps) {
  return (
    <Card className="border-2">
      <CardHeader className="bg-gradient-to-r from-blue-50 to-indigo-50 pb-4">
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <CardTitle className="text-base flex items-center gap-2 mb-3">
              <Package className="h-4 w-4 text-blue-600" />
              범위 조건 #{index + 1}
            </CardTitle>
            
            {/* 범위 기본 정보 */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div>
                <Label className="text-xs text-muted-foreground">최소값</Label>
                <Input
                  type="number"
                  value={range.minValue || 0}
                  onChange={(e) =>
                    onUpdateRange(index, "minValue", parseFloat(e.target.value) || 0)
                  }
                  placeholder="0"
                  className="h-9 bg-white"
                />
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">최대값</Label>
                <Input
                  type="number"
                  value={range.maxValue || 0}
                  onChange={(e) =>
                    onUpdateRange(index, "maxValue", parseFloat(e.target.value) || 0)
                  }
                  placeholder="100"
                  className="h-9 bg-white"
                />
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">범위 설명</Label>
                <Input
                  type="text"
                  value={range.description || ""}
                  onChange={(e) => onUpdateRange(index, "description", e.target.value)}
                  placeholder="예: 0~100kg"
                  className="h-9 bg-white"
                />
              </div>
            </div>

            {/* 1단계 규칙인 경우 결과 타입 선택 */}
            {isStage1 && (
              <div className="mt-3">
                <Label className="text-xs text-muted-foreground">결과 타입</Label>
                <Select
                  value={range.resultType || stage1ResultType || 'specification'}
                  onValueChange={(value: any) => onUpdateRange(index, "resultType", value)}
                >
                  <SelectTrigger className="h-9 bg-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="specification">규격</SelectItem>
                    <SelectItem value="item">품목</SelectItem>
                    <SelectItem value="quantity">수량</SelectItem>
                    <SelectItem value="value">값</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* 결과값 (규격) - 1단계에서 규격 타입일 때만 */}
            {(!isStage1 || range.resultType === 'specification' || !range.resultType) && (
              <div className="mt-3">
                <Label className="text-xs text-muted-foreground">결과값 (규격)</Label>
                <Input
                  type="text"
                  value={range.result as string}
                  onChange={(e) => onUpdateRange(index, "result", e.target.value)}
                  placeholder="예: 4인치, Φ30"
                  className="h-9 bg-white"
                />
              </div>
            )}
          </div>
          
          {/* 범위 삭제 버튼 */}
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => onDeleteRange(index)}
            className="ml-2"
          >
            <Trash2 className="h-4 w-4 text-red-600" />
          </Button>
        </div>
      </CardHeader>

      {/* 품목 목록 - 1단계 규칙이고 규격 타입이 아닐 때만 표시 */}
      {!(isStage1 && (range.resultType === 'specification' || !range.resultType)) && (
        <CardContent className="pt-4">
          <div className="space-y-3">
            <div className="flex items-center justify-between mb-2">
              <Label className="text-sm flex items-center gap-2">
                <Package className="h-4 w-4 text-blue-600" />
                품목 목록
              </Label>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => onAddItem(index)}
              >
                <Plus className="h-3 w-3 mr-1" />
                품목 추가
              </Button>
            </div>

            {/* 품목이 없을 때 */}
            {(!range.items || range.items.length === 0) && (
              <div className="text-center py-8 border-2 border-dashed rounded-lg bg-gray-50">
                <Package className="h-8 w-8 mx-auto text-gray-400 mb-2" />
                <p className="text-sm text-muted-foreground">
                  등록된 품목이 없습니다
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  "품목 추가" 버튼을 눌러 품목을 등록하세요
                </p>
              </div>
            )}

            {/* 품목 카드 목록 */}
            {range.items && range.items.length > 0 && (
              <div className="space-y-2">
                {range.items.map((item, itemIndex) => (
                  <Card key={item.id} className="border bg-white">
                    <CardContent className="pt-4">
                      <div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-start">
                        {/* 품목 선택 */}
                        <div className="md:col-span-6">
                          <Label className="text-xs text-muted-foreground">품목</Label>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button
                                variant="outline"
                                role="combobox"
                                className="w-full justify-between h-9"
                              >
                                {item.itemCode
                                  ? `[${item.itemCode}] ${item.itemName}`
                                  : "품목 선택..."}
                                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-[400px] p-0" align="start">
                              <Command>
                                <CommandInput placeholder="품목 코드 또는 품명으로 검색..." />
                                <CommandList>
                                  <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                                  
                                  {/* 가이드레일 (스크린 120×70) */}
                                  <CommandGroup heading="가이드레일 (스크린 120×70)">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          m.itemCategory === "가이드레일" &&
                                          (m as any).productType === "스크린" &&
                                          (m as any).baseSpec === "120×70",
                                      )
                                      .sort((a, b) =>
                                        ((a as any).baseType || '').localeCompare((b as any).baseType || ''),
                                      )
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName} ${master.specification || ""}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          <Badge variant="outline" className="mr-2 text-xs">
                                            {(master as any).baseType || '-'}
                                          </Badge>
                                          {master.specification || master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 가이드레일 (스크린 120×120) */}
                                  <CommandGroup heading="가이드레일 (스크린 120×120)">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          m.itemCategory === "가이드레일" &&
                                          (m as any).productType === "스크린" &&
                                          (m as any).baseSpec === "120×120",
                                      )
                                      .sort((a, b) =>
                                        ((a as any).baseType || '').localeCompare((b as any).baseType || ''),
                                      )
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName} ${master.specification || ""}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          <Badge variant="outline" className="mr-2 text-xs">
                                            {(master as any).baseType || '-'}
                                          </Badge>
                                          {master.specification || master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 가이드레일 (철재 130×75) */}
                                  <CommandGroup heading="가이드레일 (철재 130×75)">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          m.itemCategory === "가이드레일" &&
                                          (m as any).productType === "철재" &&
                                          (m as any).baseSpec === "130×75",
                                      )
                                      .sort((a, b) =>
                                        ((a as any).baseType || '').localeCompare((b as any).baseType || ''),
                                      )
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName} ${master.specification || ""}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          <Badge variant="outline" className="mr-2 text-xs">
                                            {(master as any).baseType || '-'}
                                          </Badge>
                                          {master.specification || master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 가이드레일 (철재 130×125) */}
                                  <CommandGroup heading="가이드레일 (철재 130×125)">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          m.itemCategory === "가이드레일" &&
                                          (m as any).productType === "철재" &&
                                          (m as any).baseSpec === "130×125",
                                      )
                                      .sort((a, b) =>
                                        ((a as any).baseType || '').localeCompare((b as any).baseType || ''),
                                      )
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName} ${master.specification || ""}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          <Badge variant="outline" className="mr-2 text-xs">
                                            {(master as any).baseType || '-'}
                                          </Badge>
                                          {master.specification || master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 모터 */}
                                  <CommandGroup heading="모터 품목">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          m.itemCode.startsWith("MOTOR-"),
                                      )
                                      .sort((a, b) => a.itemCode.localeCompare(b.itemCode))
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          {master.itemCode} - {master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 브라켓 */}
                                  <CommandGroup heading="브라켓 품목">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          (m.itemCode.startsWith("BRACKET-") || m.itemCode.includes("브라켓")),
                                      )
                                      .sort((a, b) => a.itemCode.localeCompare(b.itemCode))
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          {master.itemCode} - {master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 받침용앵글 */}
                                  <CommandGroup heading="받침용앵글 품목">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          (m.itemCode.startsWith("ANGLE-") || m.itemCode.includes("앵글")),
                                      )
                                      .sort((a, b) => a.itemCode.localeCompare(b.itemCode))
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          {master.itemCode} - {master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>

                                  {/* 기타 부품 */}
                                  <CommandGroup heading="기타 부품">
                                    {itemMasters
                                      .filter(
                                        (m) =>
                                          m.itemType === "PT" &&
                                          !m.itemCode.startsWith("R") &&
                                          !m.itemCode.startsWith("S") &&
                                          !m.itemCode.startsWith("MOTOR-") &&
                                          !m.itemCode.startsWith("BRACKET-") &&
                                          !m.itemCode.startsWith("ANGLE-") &&
                                          !m.itemCode.includes("브라켓") &&
                                          !m.itemCode.includes("앵글") &&
                                          m.itemCategory !== "가이드레일",
                                      )
                                      .sort((a, b) => a.itemCode.localeCompare(b.itemCode))
                                      .map((master) => (
                                        <CommandItem
                                          key={master.id}
                                          value={`${master.itemCode} ${master.itemName}`}
                                          onSelect={() => {
                                            onUpdateItem(index, itemIndex, "itemCode", master.itemCode);
                                            onUpdateItem(index, itemIndex, "itemName", master.itemName);
                                          }}
                                        >
                                          <Check
                                            className={`mr-2 h-4 w-4 ${
                                              item.itemCode === master.itemCode
                                                ? "opacity-100"
                                                : "opacity-0"
                                            }`}
                                          />
                                          {master.itemCode} - {master.itemName}
                                        </CommandItem>
                                      ))}
                                  </CommandGroup>
                                </CommandList>
                              </Command>
                            </PopoverContent>
                          </Popover>
                        </div>

                        {/* 수량 */}
                        <div className="md:col-span-2">
                          <Label className="text-xs text-muted-foreground">수량</Label>
                          <Input
                            type="text"
                            value={item.quantity || "1"}
                            onChange={(e) =>
                              onUpdateItem(index, itemIndex, "quantity", e.target.value || "1")
                            }
                            placeholder="1 또는 수식"
                            className="h-9"
                          />
                        </div>

                        {/* 비고 */}
                        <div className="md:col-span-3">
                          <Label className="text-xs text-muted-foreground">비고</Label>
                          <Input
                            type="text"
                            value={item.note || ""}
                            onChange={(e) =>
                              onUpdateItem(index, itemIndex, "note", e.target.value)
                            }
                            placeholder="비고"
                            className="h-9"
                          />
                        </div>

                        {/* 삭제 버튼 */}
                        <div className="md:col-span-1 flex items-end">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => onDeleteItem(index, itemIndex)}
                            className="w-full h-9"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </CardContent>
      )}

      {/* 다중 조건 입력 */}
      {!(isStage1 && (range.resultType === 'specification' || !range.resultType)) && (
        <CardContent className="pt-0 border-t">
          <MultiConditionInput
            conditions={range.additionalConditions || []}
            onConditionsChange={(conditions) =>
              onUpdateRange(index, "additionalConditions", conditions)
            }
          />
        </CardContent>
      )}
    </Card>
  );
}
