import React, { useState, useEffect } from "react";
import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Switch } from "./ui/switch";
import { Calendar, ArrowLeft, Upload, CheckCircle2, AlertCircle, RefreshCw } from "lucide-react";
import { toast } from "sonner@2.0.3";
import { motion } from "motion/react";
import { generateAutoCode, checkAndResetSequence } from "./utils/codeGenerator";

// 입고등록 페이지
interface ReceivingWritePageProps {
  onBack: () => void;
  onInspection: (data: any) => void;
}

export function ReceivingWritePage({ onBack, onInspection }: ReceivingWritePageProps) {
  const [itemCode, setItemCode] = useState("");
  const [itemName, setItemName] = useState("");
  const [receivingDate, setReceivingDate] = useState(new Date().toISOString().split("T")[0]);
  const [receivingUnit, setReceivingUnit] = useState("EA");
  const [receivingQty, setReceivingQty] = useState("");
  const [spec, setSpec] = useState("");
  const [properties, setProperties] = useState("");
  const [additionalNotes, setAdditionalNotes] = useState("");
  const [supplier, setSupplier] = useState("");
  const [manager, setManager] = useState("");
  const [manufacturer, setManufacturer] = useState("");
  const [lotNumber, setLotNumber] = useState("");
  const [materialNumber, setMaterialNumber] = useState("");
  const [inspectionEnabled, setInspectionEnabled] = useState(false);

  // 컴포넌트 마운트 시 순번 초기화 체크
  useEffect(() => {
    checkAndResetSequence();
  }, []);

  // 검사대상 토글 시 자동으로 코드 생성
  useEffect(() => {
    if (inspectionEnabled && !lotNumber) {
      const generatedLotCode = generateAutoCode("로트코드");
      setLotNumber(generatedLotCode);
      
      const generatedMaterialCode = generateAutoCode("자재번호");
      setMaterialNumber(generatedMaterialCode);
      
      toast.success("로트코드와 자재번호가 자동 생성되었습니다.");
    }
  }, [inspectionEnabled]);

  // 코드 재생성 함수
  const regenerateLotCode = () => {
    const newCode = generateAutoCode("로트코드");
    setLotNumber(newCode);
    toast.success("로트코드가 재생성되었습니다.");
  };

  const regenerateMaterialCode = () => {
    const newCode = generateAutoCode("자재번호");
    setMaterialNumber(newCode);
    toast.success("자재번호가 재생성되었습니다.");
  };

  // 검증 없이 바로 수입검사로 이동
  const handleGoToInspection = () => {
    toast.info("수입검사 화면으로 이동합니다.");
    
    setTimeout(() => {
      onInspection({
        itemName: itemName || itemCode || "입고 품목",
        itemCode: itemCode || "-",
        spec: spec || "-",
        properties: properties || "-",
        lotNumber: lotNumber || "-",
        materialNumber: materialNumber || "-",
        receivingDate,
        receivingQty: receivingQty || "0",
        receivingUnit,
        supplier: supplier || "미등록",
        manufacturer: manufacturer || "미등록"
      });
    }, 300);
  };

  const handleSubmit = () => {
    // 필수 필드 검증
    if (!itemCode) {
      toast.error("품목을 선택해주세요.");
      return;
    }
    if (!receivingQty) {
      toast.error("입고량을 입력해주세요.");
      return;
    }

    // 검사대상 자재인 경우 추가 검증
    if (inspectionEnabled) {
      if (!lotNumber) {
        toast.error("로트번호를 입력해주세요.");
        return;
      }
      if (!materialNumber) {
        toast.error("자재번호를 입력해주세요.");
        return;
      }

      // 수입검사로 이동
      toast.success("입고 등록이 완료되었습니다. 수입검사를 진행합니다.");
      
      setTimeout(() => {
        onInspection({
          itemName: itemName || itemCode,
          itemCode,
          spec,
          properties,
          lotNumber,
          materialNumber,
          receivingDate,
          receivingQty,
          receivingUnit,
          supplier: supplier || "미등록",
          manufacturer: manufacturer || "미등록"
        });
      }, 500);
    } else {
      // 바로 입고 처리
      toast.success("입고가 완료되었습니다.");
      setTimeout(() => {
        onBack();
      }, 1000);
    }
  };

  return (
    <div className="space-y-4 md:space-y-6 pb-6">
      {/* 헤더 */}
      <div className="flex items-center gap-3 md:gap-4">
        <Button variant="ghost" size="icon" onClick={onBack} className="shrink-0">
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex-1 min-w-0">
          <h1 className="text-2xl md:text-3xl font-bold truncate">입고 등록</h1>
          <p className="text-xs md:text-sm text-muted-foreground mt-1">
            자재 입고 정보를 등록합니다
          </p>
        </div>
      </div>

      {/* 프로세스 스텝 인디케이터 */}
      <div className="flex items-center justify-center gap-2 py-4">
        <div className="flex items-center gap-2">
          <div className="flex items-center justify-center w-8 h-8 rounded-full bg-blue-600 text-white text-sm font-semibold">
            1
          </div>
          <span className="text-sm font-medium hidden sm:inline">입고 등록</span>
        </div>
        
        {inspectionEnabled && (
          <>
            <div className="w-12 md:w-20 h-0.5 bg-blue-600" />
            <div className="flex items-center gap-2">
              <div className="flex items-center justify-center w-8 h-8 rounded-full bg-blue-100 text-blue-600 border-2 border-blue-600 text-sm font-semibold">
                2
              </div>
              <span className="text-sm font-medium text-blue-600 hidden sm:inline">수입검사</span>
            </div>
          </>
        )}
        
        <div className={`w-12 md:w-20 h-0.5 ${inspectionEnabled ? 'bg-gray-300' : 'bg-blue-600'}`} />
        <div className="flex items-center gap-2">
          <div className={`flex items-center justify-center w-8 h-8 rounded-full text-sm font-semibold ${
            inspectionEnabled ? 'bg-gray-200 text-gray-400' : 'bg-blue-100 text-blue-600 border-2 border-blue-600'
          }`}>
            {inspectionEnabled ? '3' : '2'}
          </div>
          <span className={`text-sm font-medium hidden sm:inline ${
            inspectionEnabled ? 'text-gray-400' : 'text-blue-600'
          }`}>완료</span>
        </div>
      </div>

      <Card>
        <CardContent className="p-4 md:p-6 space-y-6">
          {/* 검사대상 자재 - 상단으로 이동 */}
          <div className="space-y-3">
            <div className="flex items-start gap-3 p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200 rounded-lg hover:shadow-md transition-shadow">
              <Switch
                checked={inspectionEnabled}
                onCheckedChange={setInspectionEnabled}
                id="inspection-toggle"
                className="mt-1"
              />
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <Label htmlFor="inspection-toggle" className="cursor-pointer text-base font-semibold">
                    검사대상 자재
                  </Label>
                  <AlertCircle className="w-4 h-4 text-blue-600" />
                </div>
                <p className="text-sm text-muted-foreground mt-1">
                  {inspectionEnabled 
                    ? "✓ 입고 후 수입검사가 진행됩니다 (3단계 프로세스)" 
                    : "○ 검사 없이 바로 입고됩니다 (2단계 프로세스)"}
                </p>
                <div className="flex items-center gap-2 mt-2 text-xs text-blue-700">
                  <span className={inspectionEnabled ? "font-semibold" : ""}>
                    {inspectionEnabled ? "로트번호 및 자재번호가 필수로 입력됩니다" : "간편 입고 모드"}
                  </span>
                </div>
              </div>
              {inspectionEnabled && (
                <Badge className="ml-2 bg-blue-600 shrink-0 animate-pulse">
                  수입검사 필요
                </Badge>
              )}
            </div>
          </div>

          {/* 품목 */}
          <div className="space-y-3">
            <Label className="text-base font-semibold">품목</Label>
            <div className="grid grid-cols-1 gap-4">
              <div className="space-y-2">
                <Label>품목 코드 <span className="text-red-500">*</span></Label>
                <Select value={itemCode} onValueChange={setItemCode}>
                  <SelectTrigger>
                    <SelectValue placeholder="품목을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="EGIT-SST">EGIT-SST</SelectItem>
                    <SelectItem value="KSS-01">KSS-01</SelectItem>
                    <SelectItem value="MAT-2024-001">MAT-2024-001</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>품목명</Label>
                <Input
                  placeholder="예: 분체 파우더"
                  value={itemName}
                  onChange={(e) => setItemName(e.target.value)}
                />
              </div>
            </div>
          </div>

          {/* 기본 정보 */}
          <div className="space-y-3">
            <Label className="text-base font-semibold">기본 정보</Label>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>입고일자 <span className="text-red-500">*</span></Label>
                <div className="relative">
                  <Input
                    type="date"
                    value={receivingDate}
                    onChange={(e) => setReceivingDate(e.target.value)}
                    className="pr-10"
                  />
                  <Calendar className="absolute right-3 top-3 h-4 w-4 text-muted-foreground pointer-events-none" />
                </div>
              </div>

              <div className="space-y-2">
                <Label>규격</Label>
                <Input
                  placeholder="예: 1219*3500"
                  value={spec}
                  onChange={(e) => setSpec(e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label>입고단위 <span className="text-red-500">*</span></Label>
                <Select value={receivingUnit} onValueChange={setReceivingUnit}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="EA">EA</SelectItem>
                    <SelectItem value="kg">kg</SelectItem>
                    <SelectItem value="m">m</SelectItem>
                    <SelectItem value="L">L</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>입고량 <span className="text-red-500">*</span></Label>
                <Input
                  placeholder="0"
                  value={receivingQty}
                  onChange={(e) => setReceivingQty(e.target.value)}
                  type="number"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>추가 기록</Label>
              <Textarea
                placeholder="물리적 특성, 화학 성분, 용도 등"
                value={additionalNotes}
                onChange={(e) => setAdditionalNotes(e.target.value)}
                rows={3}
                className="resize-none"
              />
              <p className="text-xs text-muted-foreground">
                * 입고 및 나중에 연속 필드를 추가해서 별도 보시할 수 있습니다
              </p>
            </div>
          </div>

          {/* 납품업체 */}
          <div className="space-y-3">
            <Label className="text-base font-semibold">납품업체</Label>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label>납품업체</Label>
                <Input
                  placeholder="예: 거주자스톡"
                  value={supplier}
                  onChange={(e) => setSupplier(e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label>담당자</Label>
                <Input
                  placeholder="예: 입고 담당"
                  value={manager}
                  onChange={(e) => setManager(e.target.value)}
                />
              </div>

              <div className="space-y-2 sm:col-span-2 lg:col-span-1">
                <Label>제조사</Label>
                <Input
                  placeholder="예: KG스틸 등"
                  value={manufacturer}
                  onChange={(e) => setManufacturer(e.target.value)}
                />
              </div>
            </div>
          </div>

          {/* 검사대상 자재 활성화 시 추가 필드 */}
          {inspectionEnabled && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.3 }}
              className="space-y-6"
            >
              {/* 로트 정보 */}
              <div className="space-y-3 p-4 bg-amber-50 border-2 border-amber-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-amber-600" />
                  <Label className="text-base font-semibold text-amber-900">로트 정보 (검사대상 필수)</Label>
                </div>
                <div className="grid grid-cols-1 gap-4">
                  <div className="space-y-2">
                    <Label>로트 번호 <span className="text-red-500">*</span></Label>
                    <div className="flex gap-2">
                      <Input
                        value={lotNumber}
                        onChange={(e) => setLotNumber(e.target.value)}
                        placeholder="자동 생성됨"
                        className="flex-1"
                      />
                      <Button 
                        type="button"
                        variant="outline" 
                        size="icon"
                        onClick={regenerateLotCode}
                        title="로트코드 재생성"
                        className="shrink-0"
                      >
                        <RefreshCw className="h-4 w-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      자동 생성되며, 기준정보 &gt; 코드관리에서 형식을 변경할 수 있습니다
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label>자재번호 (로트 마킹용) <span className="text-red-500">*</span></Label>
                    <div className="flex gap-2">
                      <Input
                        value={materialNumber}
                        onChange={(e) => setMaterialNumber(e.target.value)}
                        placeholder="자동 생성됨"
                        className="flex-1"
                      />
                      <Button 
                        type="button"
                        variant="outline" 
                        size="icon"
                        onClick={regenerateMaterialCode}
                        title="자재번호 재생성"
                        className="shrink-0"
                      >
                        <RefreshCw className="h-4 w-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      자동 생성되며, 기준정보 &gt; 코드관리에서 형식을 변경할 수 있습니다
                    </p>
                  </div>
                </div>
              </div>

              {/* 품질 업로드 */}
              <div className="space-y-3 p-4 bg-green-50 border-2 border-green-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-green-600" />
                  <Label className="text-base font-semibold text-green-900">
                    품질 문서 업로드 (선택사항)
                  </Label>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="text-sm">원산지 업로드</Label>
                    <div className="border-2 border-dashed border-muted-foreground/25 rounded-lg p-6 text-center hover:border-muted-foreground/50 transition-colors cursor-pointer">
                      <Upload className="h-8 w-8 mx-auto mb-2 text-muted-foreground" />
                      <p className="text-xs text-muted-foreground mb-1">
                        클릭하거나 드래그
                      </p>
                      <p className="text-xs text-muted-foreground">
                        PDF, JPG, PNG (최대 10MB)
                      </p>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label className="text-sm">가열명세표 업로드</Label>
                    <div className="border-2 border-dashed border-muted-foreground/25 rounded-lg p-6 text-center hover:border-muted-foreground/50 transition-colors cursor-pointer">
                      <Upload className="h-8 w-8 mx-auto mb-2 text-muted-foreground" />
                      <p className="text-xs text-muted-foreground mb-1">
                        클릭하거나 드래그
                      </p>
                      <p className="text-xs text-muted-foreground">
                        PDF, JPG, PNG (최대 10MB)
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          )}

          {/* 하단 버튼 */}
          <div className="flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-end gap-3 pt-6 border-t">
            <Button variant="outline" onClick={onBack} className="w-full sm:w-auto">
              이전으로
            </Button>
            
            {inspectionEnabled ? (
              <>
                <Button
                  onClick={handleSubmit}
                  variant="outline"
                  className="w-full sm:w-auto"
                >
                  ✓ 입고 완료 (검증)
                </Button>
                <Button
                  onClick={handleGoToInspection}
                  className="w-full sm:w-auto bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700"
                >
                  다음: 수입검사 →
                </Button>
              </>
            ) : (
              <Button
                onClick={handleSubmit}
                className="w-full sm:w-auto bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700"
              >
                ✓ 입고 완료
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
