import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } 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 { Textarea } from "./ui/textarea";
import { Badge } from "./ui/badge";
import { ArrowLeft, Save, X, AlertCircle, Package, Building2, Factory } from "lucide-react";
import { toast } from "sonner@2.0.3";

interface MaterialRegistrationProps {
  onBack: () => void;
}

export function MaterialRegistration({ onBack }: MaterialRegistrationProps) {
  // 폼 상태 관리
  const [formData, setFormData] = useState({
    materialCode: "",
    materialName: "",
    itemName: "",
    specification: "",
    properties: "",
    additionalNotes: "",
    category: "",
    unit: "",
    unitPrice: "",
    safetyStock: "",
    maxStock: "",
    supplier: "",
    manufacturer: "",
    location: "",
    leadTime: "",
    orderPoint: ""
  });

  // 폼 필드 업데이트
  const updateField = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 필수 필드 검증
  const validateForm = () => {
    const requiredFields = [
      { field: "materialCode", label: "자재 코드" },
      { field: "materialName", label: "자재명" },
      { field: "itemName", label: "품목명" },
      { field: "specification", label: "규격" },
      { field: "category", label: "카테고리" },
      { field: "unit", label: "단위" },
      { field: "unitPrice", label: "단가" },
      { field: "supplier", label: "납품업체" },
      { field: "manufacturer", label: "제조사" }
    ];

    for (const { field, label } of requiredFields) {
      if (!formData[field as keyof typeof formData]) {
        toast.error(`${label}을(를) 입력해주세요.`);
        return false;
      }
    }
    return true;
  };

  // 저장 처리
  const handleSave = () => {
    if (!validateForm()) return;

    // 실제로는 API 호출
    console.log("자재 등록:", formData);
    toast.success("자재가 성공적으로 등록되었습니다.");
    
    // 목록으로 돌아가기
    setTimeout(() => {
      onBack();
    }, 1000);
  };

  // 취소 처리
  const handleCancel = () => {
    if (Object.values(formData).some(value => value !== "")) {
      if (confirm("작성 중인 내용이 있습니다. 정말 취소하시겠습니까?")) {
        onBack();
      }
    } else {
      onBack();
    }
  };

  // Mock 공급업체 데이터
  const suppliers = [
    { id: "SUP001", code: "SUP001", name: "ABC분체" },
    { id: "SUP002", code: "SUP002", name: "모터텍" },
    { id: "SUP003", code: "SUP003", name: "알텍솔루션" },
    { id: "SUP004", code: "SUP004", name: "케이스원" },
    { id: "SUP005", code: "SUP005", name: "마감재산업" },
    { id: "SUP006", code: "SUP006", name: "한국철강" },
    { id: "SUP007", code: "SUP007", name: "글로벌자재" }
  ];

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={onBack}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold">신규 자재 등록</h1>
            <p className="text-muted-foreground mt-1">
              자재의 기본 정보와 상세 정보를 입력하세요
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={handleCancel}>
            <X className="w-4 h-4 mr-2" />
            취소
          </Button>
          <Button onClick={handleSave}>
            <Save className="w-4 h-4 mr-2" />
            저장
          </Button>
        </div>
      </div>

      {/* 안내 메시지 */}
      <div className="bg-blue-50 dark:bg-blue-950/20 p-4 rounded-lg border border-blue-200 dark:border-blue-800">
        <div className="flex items-start space-x-3">
          <AlertCircle className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
          <div>
            <h3 className="font-bold text-blue-900 dark:text-blue-100">필수 정보 안내</h3>
            <p className="text-sm text-blue-700 dark:text-blue-300 mt-1">
              <span className="text-red-500">*</span> 표시가 있는 항목은 필수 입력 항목입니다.
            </p>
          </div>
        </div>
      </div>

      {/* 등록 폼 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 왼쪽: 기본 정보 */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <div className="flex items-center gap-2">
              <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
                <Package className="h-5 w-5 text-white" />
              </div>
              <div>
                <CardTitle>기본 정보</CardTitle>
                <CardDescription>자재의 기본 정보를 입력하세요</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 자재 코드 & 자재명 */}
            <div className="grid grid-cols-1 gap-4">
              <div className="space-y-2">
                <Label htmlFor="materialCode">
                  자재 코드 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="materialCode"
                  placeholder="예: MAT-001"
                  value={formData.materialCode}
                  onChange={(e) => updateField("materialCode", e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  고유한 자재 식별 코드를 입력하세요
                </p>
              </div>
              <div className="space-y-2">
                <Label htmlFor="materialName">
                  자재명 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="materialName"
                  placeholder="자재명 입력"
                  value={formData.materialName}
                  onChange={(e) => updateField("materialName", e.target.value)}
                />
              </div>
            </div>

            {/* 품목명 & 규격 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="itemName">
                  품목명 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="itemName"
                  placeholder="예: 분체 파우더"
                  value={formData.itemName}
                  onChange={(e) => updateField("itemName", e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="specification">
                  규격 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="specification"
                  placeholder="예: RAL 9010, 200메쉬"
                  value={formData.specification}
                  onChange={(e) => updateField("specification", e.target.value)}
                />
              </div>
            </div>

            {/* 속성 & 카테고리 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="properties">속성</Label>
                <Input
                  id="properties"
                  placeholder="예: 내열성, 내후성"
                  value={formData.properties}
                  onChange={(e) => updateField("properties", e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="category">
                  카테고리 <span className="text-red-500">*</span>
                </Label>
                <Select value={formData.category} onValueChange={(value) => updateField("category", value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="카테고리 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="분체">분체</SelectItem>
                    <SelectItem value="모터">모터</SelectItem>
                    <SelectItem value="가이드레일">가이드레일</SelectItem>
                    <SelectItem value="케이스">케이스</SelectItem>
                    <SelectItem value="하단마감재">하단마감재</SelectItem>
                    <SelectItem value="부자재">부자재</SelectItem>
                    <SelectItem value="전장품">전장품</SelectItem>
                    <SelectItem value="원자재">원자재</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 추가 기록 */}
            <div className="space-y-2">
              <Label htmlFor="additionalNotes">추가 기록</Label>
              <Textarea
                id="additionalNotes"
                placeholder="자재 관련 추가 정보를 입력하세요 (예: 실내 사용 권장, 온도 -40~80°C 등)"
                rows={4}
                value={formData.additionalNotes}
                onChange={(e) => updateField("additionalNotes", e.target.value)}
              />
              <p className="text-xs text-muted-foreground">
                특이사항, 보관 조건, 주의사항 등을 자유롭게 입력할 수 있습니다
              </p>
            </div>
          </CardContent>
        </Card>

        {/* 오른쪽: 공급업체 & 제조사 정보 */}
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-lg flex items-center justify-center">
                  <Building2 className="h-5 w-5 text-white" />
                </div>
                <div>
                  <CardTitle>공급업체 정보</CardTitle>
                  <CardDescription>납품업체 및 제조사</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="supplier">
                  납품업체 <span className="text-red-500">*</span>
                </Label>
                <Select value={formData.supplier} onValueChange={(value) => updateField("supplier", value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="납품업체 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {suppliers.map((supplier) => (
                      <SelectItem key={supplier.id} value={supplier.code}>
                        {supplier.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="manufacturer">
                  제조사 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="manufacturer"
                  placeholder="예: 한국분체공업(주)"
                  value={formData.manufacturer}
                  onChange={(e) => updateField("manufacturer", e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="leadTime">리드타임 (일)</Label>
                <Input
                  id="leadTime"
                  type="number"
                  placeholder="예: 7"
                  value={formData.leadTime}
                  onChange={(e) => updateField("leadTime", e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  발주 후 입고까지 소요 일수
                </p>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <div className="flex items-center gap-2">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg flex items-center justify-center">
                  <Factory className="h-5 w-5 text-white" />
                </div>
                <div>
                  <CardTitle>재고 관리</CardTitle>
                  <CardDescription>재고 및 단가 정보</CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="unit">
                    단위 <span className="text-red-500">*</span>
                  </Label>
                  <Select value={formData.unit} onValueChange={(value) => updateField("unit", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="단위 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="EA">EA</SelectItem>
                      <SelectItem value="M">M</SelectItem>
                      <SelectItem value="KG">KG</SelectItem>
                      <SelectItem value="L">L</SelectItem>
                      <SelectItem value="BOX">BOX</SelectItem>
                      <SelectItem value="SET">SET</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="unitPrice">
                    단가 <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="unitPrice"
                    type="number"
                    placeholder="10000"
                    value={formData.unitPrice}
                    onChange={(e) => updateField("unitPrice", e.target.value)}
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="safetyStock">안전재고</Label>
                  <Input
                    id="safetyStock"
                    type="number"
                    placeholder="50"
                    value={formData.safetyStock}
                    onChange={(e) => updateField("safetyStock", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="maxStock">최대재고</Label>
                  <Input
                    id="maxStock"
                    type="number"
                    placeholder="200"
                    value={formData.maxStock}
                    onChange={(e) => updateField("maxStock", e.target.value)}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="orderPoint">발주점</Label>
                <Input
                  id="orderPoint"
                  type="number"
                  placeholder="60"
                  value={formData.orderPoint}
                  onChange={(e) => updateField("orderPoint", e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  이 수량 이하로 재고가 떨어지면 발주 알림
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="location">보관위치</Label>
                <Input
                  id="location"
                  placeholder="예: A-01-01"
                  value={formData.location}
                  onChange={(e) => updateField("location", e.target.value)}
                />
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* 하단 액션 버튼 (모바일용) */}
      <div className="lg:hidden flex gap-2">
        <Button variant="outline" className="flex-1" onClick={handleCancel}>
          <X className="w-4 h-4 mr-2" />
          취소
        </Button>
        <Button className="flex-1" onClick={handleSave}>
          <Save className="w-4 h-4 mr-2" />
          저장
        </Button>
      </div>
    </div>
  );
}