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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Calendar } from "./ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { format } from "date-fns";
import { ko } from "date-fns/locale";
import exampleImage from 'figma:asset/f45b226177bda48b8e567127fc4bd99692ba9b49.png';
import { 
  ArrowLeft,
  FileText,
  Trash2,
  Copy,
  Calendar as CalendarIcon,
  Save,
  Plus,
  X,
  Search
} from "lucide-react";

interface BOMPart {
  id: string;
  name: string;
  material: string;
  elongationSum: number;
  developmentSum: number;
  elongationDevelopmentSum: number;
  pricePerArea: number;
  price: number;
  quantity: number;
  totalPrice: number;
}

interface BOM {
  id: string;
  majorCategory: string;
  middleCategory: string;
  modelName: string;
  specification: string;
  size: string;
  boxWidth: number;
  boxHeight: number;
  frontPanelIndex: number;
  railWidth: number;
  finish: string;
  unitPrice: number;
  priceDate: string;
  deployment: string;
  parts: BOMPart[];
  createdAt: string;
  updatedAt: string;
}

interface BOMCreatePageProps {
  bomToEdit?: BOM | null;
  onBack?: () => void;
  onSave?: (bomData: BOM) => void;
}

export function BOMCreatePage({ bomToEdit = null, onBack, onSave }: BOMCreatePageProps) {
  
  // 날짜 선택
  const [priceDate, setPriceDate] = useState<Date>(bomToEdit ? new Date(bomToEdit.priceDate) : new Date());
  const [isCalendarOpen, setIsCalendarOpen] = useState(false);
  
  // BOM 데이터
  const [bomData, setBOMData] = useState<Partial<BOM>>(bomToEdit || {
    majorCategory: "대분류",
    middleCategory: "케이스",
    modelName: "KSS02",
    specification: "일반 견적권",
    size: "600*550",
    boxWidth: 600,
    boxHeight: 550,
    frontPanelIndex: 50,
    railWidth: 75,
    finish: "마감",
    unitPrice: 71604,
    priceDate: new Date().toISOString().split('T')[0],
    deployment: "",
    parts: []
  });

  // 부품 검색
  const [isPartSearchOpen, setIsPartSearchOpen] = useState(false);
  const [partSearchTerm, setPartSearchTerm] = useState("");

  // 부품 목록 (검색용)
  const availableParts = [
    { id: "1", name: "전면부", material: "SUS304", defaultPrice: 450000 },
    { id: "2", name: "레일부", material: "EGI", defaultPrice: 276000 },
    { id: "3", name: "후면 점검구", material: "SUS304", defaultPrice: 180000 },
    { id: "4", name: "측면부", material: "EGI", defaultPrice: 320000 },
    { id: "5", name: "상부 덮개", material: "SUS304", defaultPrice: 200000 },
    { id: "6", name: "하부 점검구", material: "EGI", defaultPrice: 150000 },
    { id: "7", name: "후면 코너부", material: "SUS304", defaultPrice: 120000 },
    { id: "8", name: "측면부-마구리형", material: "EGI", defaultPrice: 280000 }
  ];

  const filteredParts = availableParts.filter(part =>
    part.name.toLowerCase().includes(partSearchTerm.toLowerCase()) ||
    part.material.toLowerCase().includes(partSearchTerm.toLowerCase())
  );

  const handleAddPart = (partId: string) => {
    const part = availableParts.find(p => p.id === partId);
    if (part && bomData.parts) {
      const newPart: BOMPart = {
        id: `part-${Date.now()}`,
        name: part.name,
        material: part.material,
        elongationSum: 0,
        developmentSum: 0,
        elongationDevelopmentSum: 0,
        pricePerArea: 0,
        price: part.defaultPrice,
        quantity: 1,
        totalPrice: part.defaultPrice
      };
      setBOMData({
        ...bomData,
        parts: [...bomData.parts, newPart]
      });
    }
    setIsPartSearchOpen(false);
    setPartSearchTerm("");
  };

  const handleRemovePart = (partId: string) => {
    if (bomData.parts) {
      setBOMData({
        ...bomData,
        parts: bomData.parts.filter(p => p.id !== partId)
      });
    }
  };

  const handleUpdatePart = (partId: string, field: keyof BOMPart, value: any) => {
    if (bomData.parts) {
      const updatedParts = bomData.parts.map(part => {
        if (part.id === partId) {
          const updated = { ...part, [field]: value };
          // 총 가격 자동 계산
          if (field === 'price' || field === 'quantity') {
            updated.totalPrice = updated.price * updated.quantity;
          }
          return updated;
        }
        return part;
      });
      setBOMData({
        ...bomData,
        parts: updatedParts
      });
    }
  };

  const totalBOMPrice = (bomData.parts || []).reduce((sum, part) => sum + part.totalPrice, 0);

  const handleSave = () => {
    const now = new Date();
    const dateStr = `${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
    const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    const dateTimeStr = `${dateStr} ${timeStr}`;

    const savedBOM: BOM = {
      id: bomToEdit?.id || `${Date.now()}`,
      majorCategory: bomData.majorCategory || "",
      middleCategory: bomData.middleCategory || "케이스",
      modelName: bomData.modelName || "",
      specification: bomData.specification || "",
      size: bomData.size || "",
      boxWidth: bomData.boxWidth || 0,
      boxHeight: bomData.boxHeight || 0,
      frontPanelIndex: bomData.frontPanelIndex || 0,
      railWidth: bomData.railWidth || 0,
      finish: bomData.finish || "",
      unitPrice: bomData.unitPrice || 0,
      priceDate: bomData.priceDate || "",
      deployment: bomData.deployment || "",
      parts: bomData.parts || [],
      createdAt: bomToEdit?.createdAt || dateTimeStr,
      updatedAt: dateTimeStr
    };

    if (onSave) {
      onSave(savedBOM);
    } else if (onBack) {
      onBack();
    }
  };

  const handleCopy = () => {
    const copiedBOM = {
      ...bomData,
      modelName: `${bomData.modelName}_복사`,
      id: undefined
    };
    setBOMData(copiedBOM);
  };

  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            size="sm"
            onClick={onBack}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            돌아가기
          </Button>
          <div>
            <h1 className="mb-2">
              {bomToEdit ? 'BOM 수정' : 'BOM 생성'}
            </h1>
            <p className="text-muted-foreground">
              제품의 자재 명세서(BOM)를 {bomToEdit ? '수정' : '생성'}합니다.
            </p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleCopy}>
            <Copy className="h-4 w-4 mr-2" />
            복사
          </Button>
          <Button onClick={handleSave}>
            <Save className="h-4 w-4 mr-2" />
            저장
          </Button>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
            {/* 1행 */}
            <div className="space-y-2">
              <Label>대분류 *</Label>
              <Select 
                value={bomData.majorCategory}
                onValueChange={(value) => setBOMData({...bomData, majorCategory: value})}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="대분류">대분류</SelectItem>
                  <SelectItem value="제품">제품</SelectItem>
                  <SelectItem value="부품">부품</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>중분류 *</Label>
              <Select 
                value={bomData.middleCategory}
                onValueChange={(value) => setBOMData({...bomData, middleCategory: value})}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="케이스">케이스</SelectItem>
                  <SelectItem value="패널">패널</SelectItem>
                  <SelectItem value="프레임">프레임</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>모델명 *</Label>
              <Select 
                value={bomData.modelName}
                onValueChange={(value) => setBOMData({...bomData, modelName: value})}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="KSS02">KSS02</SelectItem>
                  <SelectItem value="KSS03">KSS03</SelectItem>
                  <SelectItem value="KSS04">KSS04</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>규격 *</Label>
              <Select 
                value={bomData.specification}
                onValueChange={(value) => setBOMData({...bomData, specification: value})}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="일반 견적권">일반 견적권</SelectItem>
                  <SelectItem value="특수 견적권">특수 견적권</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>박스 폭</Label>
              <Input 
                type="number"
                value={bomData.boxWidth}
                onChange={(e) => setBOMData({...bomData, boxWidth: Number(e.target.value)})}
              />
            </div>

            <div className="space-y-2">
              <Label>마감</Label>
              <Select 
                value={bomData.finish}
                onValueChange={(value) => setBOMData({...bomData, finish: value})}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="마감">마감</SelectItem>
                  <SelectItem value="미마감">미마감</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 2행 */}
            <div className="space-y-2">
              <Label>사이즈</Label>
              <Input 
                value={bomData.size}
                onChange={(e) => setBOMData({...bomData, size: e.target.value})}
                placeholder="600*550"
              />
            </div>

            <div className="space-y-2">
              <Label>박스 높이</Label>
              <Input 
                type="number"
                value={bomData.boxHeight}
                onChange={(e) => setBOMData({...bomData, boxHeight: Number(e.target.value)})}
              />
            </div>

            <div className="space-y-2">
              <Label>전면 필 지수</Label>
              <Input 
                type="number"
                value={bomData.frontPanelIndex}
                onChange={(e) => setBOMData({...bomData, frontPanelIndex: Number(e.target.value)})}
              />
            </div>

            <div className="space-y-2">
              <Label>레일 폭</Label>
              <Input 
                type="number"
                value={bomData.railWidth}
                onChange={(e) => setBOMData({...bomData, railWidth: Number(e.target.value)})}
              />
            </div>

            <div className="space-y-2">
              <Label>단가/M</Label>
              <Input 
                type="number"
                value={bomData.unitPrice}
                onChange={(e) => setBOMData({...bomData, unitPrice: Number(e.target.value)})}
              />
            </div>

            <div className="space-y-2">
              <Label>단가기준일</Label>
              <Popover open={isCalendarOpen} onOpenChange={setIsCalendarOpen}>
                <PopoverTrigger asChild>
                  <Button variant="outline" className="w-full justify-start">
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {format(priceDate, "yy-MM-dd", { locale: ko })}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0">
                  <Calendar
                    mode="single"
                    selected={priceDate}
                    onSelect={(date) => {
                      if (date) {
                        setPriceDate(date);
                        setBOMData({
                          ...bomData,
                          priceDate: format(date, "yy-MM-dd")
                        });
                        setIsCalendarOpen(false);
                      }
                    }}
                    locale={ko}
                  />
                </PopoverContent>
              </Popover>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 구성 부품 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>구성 부품</CardTitle>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsPartSearchOpen(!isPartSearchOpen)}
            >
              <Plus className="h-4 w-4 mr-2" />
              부품 추가
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 부품 검색 */}
          {isPartSearchOpen && (
            <div className="border rounded-lg p-4 space-y-2">
              <div className="flex items-center gap-2">
                <Search className="h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="부품명 또는 재질로 검색..."
                  value={partSearchTerm}
                  onChange={(e) => setPartSearchTerm(e.target.value)}
                />
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsPartSearchOpen(false)}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
              <div className="max-h-48 overflow-y-auto space-y-1">
                {filteredParts.map((part) => (
                  <div
                    key={part.id}
                    className="flex items-center justify-between p-2 hover:bg-accent rounded cursor-pointer"
                    onClick={() => handleAddPart(part.id)}
                  >
                    <div>
                      <p className="font-medium">{part.name}</p>
                      <p className="text-sm text-muted-foreground">{part.material}</p>
                    </div>
                    <p className="text-sm">₩{part.defaultPrice.toLocaleString()}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 부품 목록 */}
          {bomData.parts && bomData.parts.length > 0 ? (
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>부품명</TableHead>
                    <TableHead>재질</TableHead>
                    <TableHead className="text-right">신장합</TableHead>
                    <TableHead className="text-right">전개합</TableHead>
                    <TableHead className="text-right">신장전개합</TableHead>
                    <TableHead className="text-right">면적당 단가</TableHead>
                    <TableHead className="text-right">가격</TableHead>
                    <TableHead className="text-center">수량</TableHead>
                    <TableHead className="text-right">합계</TableHead>
                    <TableHead className="text-center">삭제</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {bomData.parts.map((part) => (
                    <TableRow key={part.id}>
                      <TableCell>{part.name}</TableCell>
                      <TableCell>{part.material}</TableCell>
                      <TableCell className="text-right">
                        <Input
                          type="number"
                          value={part.elongationSum}
                          onChange={(e) => handleUpdatePart(part.id, 'elongationSum', Number(e.target.value))}
                          className="w-24 text-right"
                        />
                      </TableCell>
                      <TableCell className="text-right">
                        <Input
                          type="number"
                          value={part.developmentSum}
                          onChange={(e) => handleUpdatePart(part.id, 'developmentSum', Number(e.target.value))}
                          className="w-24 text-right"
                        />
                      </TableCell>
                      <TableCell className="text-right">
                        <Input
                          type="number"
                          value={part.elongationDevelopmentSum}
                          onChange={(e) => handleUpdatePart(part.id, 'elongationDevelopmentSum', Number(e.target.value))}
                          className="w-24 text-right"
                        />
                      </TableCell>
                      <TableCell className="text-right">
                        <Input
                          type="number"
                          value={part.pricePerArea}
                          onChange={(e) => handleUpdatePart(part.id, 'pricePerArea', Number(e.target.value))}
                          className="w-24 text-right"
                        />
                      </TableCell>
                      <TableCell className="text-right">
                        <Input
                          type="number"
                          value={part.price}
                          onChange={(e) => handleUpdatePart(part.id, 'price', Number(e.target.value))}
                          className="w-28 text-right"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input
                          type="number"
                          value={part.quantity}
                          onChange={(e) => handleUpdatePart(part.id, 'quantity', Number(e.target.value))}
                          className="w-20 text-center"
                        />
                      </TableCell>
                      <TableCell className="text-right font-medium">
                        ₩{part.totalPrice.toLocaleString()}
                      </TableCell>
                      <TableCell className="text-center">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemovePart(part.id)}
                        >
                          <Trash2 className="h-4 w-4 text-red-500" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                  <TableRow>
                    <TableCell colSpan={8} className="text-right font-bold">
                      총 부품 비용:
                    </TableCell>
                    <TableCell className="text-right font-bold text-lg">
                      ₩{totalBOMPrice.toLocaleString()}
                    </TableCell>
                    <TableCell />
                  </TableRow>
                </TableBody>
              </Table>
            </div>
          ) : (
            <div className="text-center py-12 border rounded-lg">
              <p className="text-muted-foreground">
                추가된 부품이 없습니다. 위의 "부품 추가" 버튼을 클릭하여 부품을 추가하세요.
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 제품 이미지 */}
      <Card>
        <CardHeader>
          <CardTitle>제품 이미지</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex justify-center">
            <img 
              src={exampleImage} 
              alt="제품 이미지" 
              className="max-h-64 w-auto border rounded-lg"
            />
          </div>
        </CardContent>
      </Card>

      {/* 하단 버튼 */}
      <div className="flex justify-end gap-2 pt-4 border-t">
        <Button variant="outline" onClick={onBack}>
          취소
        </Button>
        <Button onClick={handleSave}>
          <Save className="h-4 w-4 mr-2" />
          저장
        </Button>
      </div>
    </div>
  );
}
