/**
 * 출하 등록/수정 페이지
 * 
 * ResponsiveFormTemplate 적용
 * - 수주/분할LOT 선택 (중간검사 합격건만)
 * - 출하정보 입력
 * - 입금현황 표시
 * - 출하조건 체크
 */

import { useState, useEffect, useMemo } from "react";
import { Truck, Package, AlertCircle, CheckCircle, DollarSign, ClipboardCheck } from "lucide-react";
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 { Card, CardContent } from "./ui/card";
import { Alert, AlertDescription } from "./ui/alert";
import { Checkbox } from "./ui/checkbox";
import { toast } from "sonner@2.0.3";
import { validateForm, hasErrors } from "./utils/validation";
import { 
  ResponsiveFormTemplate, 
  FormSection, 
  FormField, 
  FormFieldGrid,
  ValidationError 
} from "./templates/ResponsiveFormTemplate";

interface ShippingData {
  id?: string;
  orderLotId: string;          // 수주LOT ID
  orderLotNo: string;          // 수주LOT 번호
  splitLotId?: string;         // 분할LOT ID
  splitLotNo?: string;         // 분할LOT 번호
  shippingDate: string;        // 출하예정일
  shippingQuantity: number;    // 출하수량
  deliveryLocation: string;    // 납품장소
  remarks?: string;            // 비고
}

interface OrderLot {
  id: string;
  lotNo: string;
  buyer: string;
  site: string;
  productName: string;
  totalQuantity: number;
  remainingQuantity: number;
  inspectionStatus: 'pending' | 'in_progress' | 'passed' | 'failed';
  creditGrade: 'A' | 'B' | 'C';
  paymentStatus: 'pending' | 'partial' | 'completed';
  paymentAmount?: number;
  totalAmount?: number;
  splitLots?: SplitLot[];
}

interface SplitLot {
  id: string;
  splitLotNo: string;
  quantity: number;
  inspectionStatus: 'pending' | 'in_progress' | 'passed' | 'failed';
}

interface ShippingRegistrationProps {
  editingShipping?: ShippingData | null;
  onSave: (data: ShippingData) => void;
  onCancel: () => void;
}

export function ShippingRegistration({ editingShipping, onSave, onCancel }: ShippingRegistrationProps) {
  const [formData, setFormData] = useState<ShippingData>({
    orderLotId: "",
    orderLotNo: "",
    shippingDate: "",
    shippingQuantity: 0,
    deliveryLocation: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
  const [selectedOrderLot, setSelectedOrderLot] = useState<OrderLot | null>(null);
  const [selectedSplitLot, setSelectedSplitLot] = useState<SplitLot | null>(null);

  // Mock 수주LOT 데이터 (중간검사 합격건만)
  const orderLots: OrderLot[] = [
    {
      id: "1",
      lotNo: "ORD-2025-A001",
      buyer: "한빛에스티",
      site: "반포3지구2공구(117동)",
      productName: "KQTS01",
      totalQuantity: 100,
      remainingQuantity: 50,
      inspectionStatus: "passed",
      creditGrade: "A",
      paymentStatus: "completed",
      paymentAmount: 50000000,
      totalAmount: 50000000,
      splitLots: [
        { id: "s1", splitLotNo: "SPLIT-001", quantity: 30, inspectionStatus: "passed" },
        { id: "s2", splitLotNo: "SPLIT-002", quantity: 20, inspectionStatus: "passed" }
      ]
    },
    {
      id: "2",
      lotNo: "ORD-2025-A002",
      buyer: "주일기업",
      site: "플라이크은평",
      productName: "KSS02",
      totalQuantity: 150,
      remainingQuantity: 100,
      inspectionStatus: "passed",
      creditGrade: "B",
      paymentStatus: "partial",
      paymentAmount: 30000000,
      totalAmount: 60000000,
      splitLots: [
        { id: "s3", splitLotNo: "SPLIT-003", quantity: 50, inspectionStatus: "passed" }
      ]
    },
    {
      id: "3",
      lotNo: "ORD-2025-A003",
      buyer: "성지금속",
      site: "한국체대부산경기장",
      productName: "KSS02",
      totalQuantity: 80,
      remainingQuantity: 75,
      inspectionStatus: "passed",
      creditGrade: "C",
      paymentStatus: "pending",
      paymentAmount: 0,
      totalAmount: 40000000
    },
    {
      id: "4",
      lotNo: "ORD-2025-A004",
      buyer: "삼진오토도어",
      site: "강진종합초교(1차)",
      productName: "KSS01",
      totalQuantity: 200,
      remainingQuantity: 120,
      inspectionStatus: "passed",
      creditGrade: "A",
      paymentStatus: "completed",
      paymentAmount: 80000000,
      totalAmount: 80000000,
      splitLots: [
        { id: "s4", splitLotNo: "SPLIT-004", quantity: 60, inspectionStatus: "passed" },
        { id: "s5", splitLotNo: "SPLIT-005", quantity: 60, inspectionStatus: "passed" }
      ]
    }
  ];

  // 중간검사 합격건만 필터링
  const passedOrderLots = useMemo(() => {
    return orderLots.filter(lot => lot.inspectionStatus === 'passed');
  }, []);

  // 수주LOT 선택 시
  const handleOrderLotChange = (lotId: string) => {
    const lot = passedOrderLots.find(l => l.id === lotId);
    if (lot) {
      setSelectedOrderLot(lot);
      setSelectedSplitLot(null);
      setFormData(prev => ({
        ...prev,
        orderLotId: lot.id,
        orderLotNo: lot.lotNo,
        splitLotId: undefined,
        splitLotNo: undefined,
        shippingQuantity: 0,
        deliveryLocation: lot.site
      }));
      setErrors(prev => ({ ...prev, orderLotId: "" }));
    }
  };

  // 분할LOT 선택 시
  const handleSplitLotChange = (splitLotId: string) => {
    if (!selectedOrderLot) return;
    
    if (splitLotId === "none") {
      setSelectedSplitLot(null);
      setFormData(prev => ({
        ...prev,
        splitLotId: undefined,
        splitLotNo: undefined,
        shippingQuantity: 0
      }));
    } else {
      const splitLot = selectedOrderLot.splitLots?.find(s => s.id === splitLotId);
      if (splitLot) {
        setSelectedSplitLot(splitLot);
        setFormData(prev => ({
          ...prev,
          splitLotId: splitLot.id,
          splitLotNo: splitLot.splitLotNo,
          shippingQuantity: 0
        }));
      }
    }
  };

  // 필드 변경 핸들러
  const handleFieldChange = (field: keyof ShippingData, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: "" }));
    }
  };

  // 유효성 검사 규칙
  const validationRules = {
    orderLotId: { required: true, label: "수주LOT" },
    shippingDate: { required: true, label: "출하예정일" },
    shippingQuantity: { 
      required: true, 
      label: "출하수량",
      custom: (value: number) => {
        if (value <= 0) return "출하수량은 0보다 커야 합니다";
        const maxQuantity = selectedSplitLot 
          ? selectedSplitLot.quantity 
          : selectedOrderLot?.remainingQuantity || 0;
        if (value > maxQuantity) {
          return `출하수량은 최대 ${maxQuantity}개까지 가능합니다`;
        }
        return null;
      }
    },
    deliveryLocation: { required: true, label: "납품장소" }
  };

  // 저장
  const handleSubmit = () => {
    const validation = validateForm(formData, validationRules);
    
    if (hasErrors(validation.errors)) {
      setErrors(validation.errors);
      const errorList: ValidationError[] = Object.entries(validation.errors).map(([field, message]) => ({
        field,
        message,
        fieldLabel: validationRules[field as keyof typeof validationRules]?.label
      }));
      setValidationErrors(errorList);
      toast.error("필수 항목을 입력해주세요");
      return;
    }

    // 출하조건 체크
    if (!checkShippingConditions()) {
      return;
    }

    onSave(formData);
    toast.success("출하가 등록되었습니다");
  };

  // 출하조건 체크
  const checkShippingConditions = (): boolean => {
    if (!selectedOrderLot) return false;

    // 신용등급 B/C이고 미입금인 경우 경고
    if ((selectedOrderLot.creditGrade === 'B' || selectedOrderLot.creditGrade === 'C') 
        && selectedOrderLot.paymentStatus === 'pending') {
      const confirmed = confirm(
        `⚠️ 출하조건 확인\n\n` +
        `거래처: ${selectedOrderLot.buyer}\n` +
        `신용등급: ${selectedOrderLot.creditGrade}\n` +
        `입금상태: 미입금\n\n` +
        `입금 확인 없이 출하를 진행하시겠습니까?`
      );
      if (!confirmed) return false;
    }

    return true;
  };

  // 에러 클릭 핸들러
  const handleErrorClick = (field: string) => {
    const element = document.getElementById(field);
    if (element) {
      element.focus();
      element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  };

  // 수주정보 표시
  const OrderLotInfo = () => {
    if (!selectedOrderLot) return null;

    const maxQuantity = selectedSplitLot 
      ? selectedSplitLot.quantity 
      : selectedOrderLot.remainingQuantity;

    return (
      <Card className="mt-4">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center justify-between pb-2 border-b">
            <span className="font-semibold">수주정보</span>
            <Badge variant="outline" className="bg-green-50">
              <CheckCircle className="h-3 w-3 mr-1" />
              검사합격
            </Badge>
          </div>
          
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div>
              <span className="text-muted-foreground">발주처:</span>
              <span className="ml-2 font-medium">{selectedOrderLot.buyer}</span>
              <Badge 
                variant="outline" 
                className={`ml-2 text-xs ${
                  selectedOrderLot.creditGrade === 'A' ? 'bg-green-50' : 
                  selectedOrderLot.creditGrade === 'B' ? 'bg-yellow-50' : 
                  'bg-red-50'
                }`}
              >
                {selectedOrderLot.creditGrade}
              </Badge>
            </div>
            <div>
              <span className="text-muted-foreground">현장:</span>
              <span className="ml-2 font-medium">{selectedOrderLot.site}</span>
            </div>
            <div>
              <span className="text-muted-foreground">제품명:</span>
              <span className="ml-2 font-medium">{selectedOrderLot.productName}</span>
            </div>
            <div>
              <span className="text-muted-foreground">총 수량:</span>
              <span className="ml-2 font-semibold">{selectedOrderLot.totalQuantity}개</span>
            </div>
            <div>
              <span className="text-muted-foreground">잔여 수량:</span>
              <span className="ml-2 font-semibold text-blue-600">
                {selectedOrderLot.remainingQuantity}개
              </span>
            </div>
            {selectedSplitLot && (
              <div>
                <span className="text-muted-foreground">분할LOT 수량:</span>
                <span className="ml-2 font-semibold text-purple-600">
                  {selectedSplitLot.quantity}개
                </span>
              </div>
            )}
          </div>

          <div className="pt-2 border-t">
            <div className="text-xs text-muted-foreground mb-1">출하 가능 수량</div>
            <div className="text-xl font-bold text-green-600">
              최대 {maxQuantity}개
            </div>
          </div>
        </CardContent>
      </Card>
    );
  };

  // 입금현황 표시
  const PaymentStatus = () => {
    if (!selectedOrderLot) return null;

    const paymentRate = selectedOrderLot.totalAmount 
      ? ((selectedOrderLot.paymentAmount || 0) / selectedOrderLot.totalAmount * 100).toFixed(0)
      : 0;

    const getPaymentBadge = (status: string) => {
      const statusMap: Record<string, { label: string; className: string }> = {
        pending: { label: "미입금", className: "bg-red-100 text-red-700 border-red-200" },
        partial: { label: "부분입금", className: "bg-orange-100 text-orange-700 border-orange-200" },
        completed: { label: "입금완료", className: "bg-green-100 text-green-700 border-green-200" }
      };
      return statusMap[status] || statusMap.pending;
    };

    const paymentBadge = getPaymentBadge(selectedOrderLot.paymentStatus);

    return (
      <Card className="mt-4 border-blue-200 bg-blue-50/30">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <DollarSign className="h-5 w-5 text-blue-600" />
              <span className="font-semibold">입금현황</span>
            </div>
            <Badge className={`${paymentBadge.className} border`}>
              {paymentBadge.label}
            </Badge>
          </div>

          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">계약금액:</span>
              <span className="font-semibold">
                {selectedOrderLot.totalAmount?.toLocaleString()}원
              </span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">입금액:</span>
              <span className="font-semibold text-green-600">
                {selectedOrderLot.paymentAmount?.toLocaleString()}원
              </span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">미수금:</span>
              <span className="font-semibold text-red-600">
                {((selectedOrderLot.totalAmount || 0) - (selectedOrderLot.paymentAmount || 0)).toLocaleString()}원
              </span>
            </div>
          </div>

          <div className="pt-2 border-t">
            <div className="text-xs text-muted-foreground mb-2">입금율</div>
            <div className="flex items-center gap-2">
              <div className="flex-1 h-3 bg-gray-200 rounded-full overflow-hidden">
                <div 
                  className={`h-full ${
                    selectedOrderLot.paymentStatus === 'completed' ? 'bg-green-500' :
                    selectedOrderLot.paymentStatus === 'partial' ? 'bg-orange-500' :
                    'bg-red-500'
                  }`}
                  style={{ width: `${paymentRate}%` }}
                />
              </div>
              <span className="text-sm font-semibold min-w-[50px] text-right">
                {paymentRate}%
              </span>
            </div>
          </div>

          {(selectedOrderLot.creditGrade === 'B' || selectedOrderLot.creditGrade === 'C') 
            && selectedOrderLot.paymentStatus !== 'completed' && (
            <Alert className="border-yellow-200 bg-yellow-50">
              <AlertCircle className="h-4 w-4 text-yellow-600" />
              <AlertDescription className="text-yellow-800 text-sm">
                신용등급 {selectedOrderLot.creditGrade} 거래처입니다. 출하 전 입금확인이 필요합니다.
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>
    );
  };

  // 출하조건 체크리스트
  const ShippingConditionChecklist = () => {
    if (!selectedOrderLot) return null;

    const conditions = [
      {
        id: "inspection",
        label: "중간검사 합격",
        checked: selectedOrderLot.inspectionStatus === 'passed',
        required: true
      },
      {
        id: "quantity",
        label: "출하수량 확인",
        checked: formData.shippingQuantity > 0 && formData.shippingQuantity <= (selectedSplitLot?.quantity || selectedOrderLot.remainingQuantity),
        required: true
      },
      {
        id: "date",
        label: "출하예정일 지정",
        checked: !!formData.shippingDate,
        required: true
      },
      {
        id: "location",
        label: "납품장소 확인",
        checked: !!formData.deliveryLocation,
        required: true
      },
      {
        id: "payment",
        label: "입금확인 (신용등급 B/C)",
        checked: selectedOrderLot.paymentStatus === 'completed' || selectedOrderLot.creditGrade === 'A',
        required: selectedOrderLot.creditGrade === 'B' || selectedOrderLot.creditGrade === 'C'
      }
    ];

    const allChecked = conditions.filter(c => c.required).every(c => c.checked);

    return (
      <Card className={`mt-4 ${allChecked ? 'border-green-200 bg-green-50/30' : 'border-orange-200 bg-orange-50/30'}`}>
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <ClipboardCheck className={`h-5 w-5 ${allChecked ? 'text-green-600' : 'text-orange-600'}`} />
              <span className="font-semibold">출하조건 체크</span>
            </div>
            {allChecked && (
              <Badge className="bg-green-100 text-green-700 border-green-200">
                <CheckCircle className="h-3 w-3 mr-1" />
                확인완료
              </Badge>
            )}
          </div>

          <div className="space-y-2">
            {conditions.map(condition => (
              <div 
                key={condition.id} 
                className="flex items-center justify-between p-2 rounded bg-white border"
              >
                <div className="flex items-center gap-2">
                  {condition.checked ? (
                    <CheckCircle className="h-4 w-4 text-green-600" />
                  ) : (
                    <AlertCircle className="h-4 w-4 text-orange-600" />
                  )}
                  <span className={`text-sm ${condition.required ? 'font-medium' : ''}`}>
                    {condition.label}
                    {condition.required && <span className="text-red-500 ml-1">*</span>}
                  </span>
                </div>
                <Badge 
                  variant="outline" 
                  className={`text-xs ${
                    condition.checked ? 'bg-green-50 text-green-700' : 'bg-gray-50 text-gray-600'
                  }`}
                >
                  {condition.checked ? '확인' : '대기'}
                </Badge>
              </div>
            ))}
          </div>

          {!allChecked && (
            <Alert className="border-orange-200 bg-orange-50">
              <AlertCircle className="h-4 w-4 text-orange-600" />
              <AlertDescription className="text-orange-800 text-sm">
                모든 필수 출하조건을 확인해주세요.
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>
    );
  };

  useEffect(() => {
    if (editingShipping) {
      setFormData(editingShipping);
      // 수주LOT 정보 로드
      const lot = passedOrderLots.find(l => l.id === editingShipping.orderLotId);
      if (lot) {
        setSelectedOrderLot(lot);
        if (editingShipping.splitLotId) {
          const splitLot = lot.splitLots?.find(s => s.id === editingShipping.splitLotId);
          if (splitLot) setSelectedSplitLot(splitLot);
        }
      }
    }
  }, [editingShipping]);

  return (
    <ResponsiveFormTemplate
      title={editingShipping ? "출하 수정" : "출하 등록"}
      description="출하정보를 입력하세요"
      icon={Truck}
      onSave={handleSubmit}
      onCancel={onCancel}
      saveText="저장"
      cancelText="취소"
      validationErrors={validationErrors}
      onErrorClick={handleErrorClick}
      maxWidth="2xl"
    >
      {/* 1. 수주 선택 */}
      <FormSection
        title="수주 선택"
        description="중간검사 합격건만 선택 가능합니다"
        icon={Package}
      >
        <FormField
          label="수주LOT"
          required
          error={errors.orderLotId}
          htmlFor="orderLotId"
          helpText="중간검사 합격된 수주LOT만 표시됩니다"
        >
          <Select 
            value={formData.orderLotId} 
            onValueChange={handleOrderLotChange}
          >
            <SelectTrigger id="orderLotId">
              <SelectValue placeholder="수주LOT를 선택하세요" />
            </SelectTrigger>
            <SelectContent>
              {passedOrderLots.length === 0 ? (
                <div className="p-4 text-sm text-muted-foreground text-center">
                  중간검사 합격된 수주LOT가 없습니다
                </div>
              ) : (
                passedOrderLots.map(lot => (
                  <SelectItem key={lot.id} value={lot.id}>
                    <div className="flex items-center justify-between w-full">
                      <div>
                        <div className="font-medium">{lot.lotNo}</div>
                        <div className="text-xs text-muted-foreground">
                          {lot.buyer} - {lot.productName} ({lot.remainingQuantity}개 잔여)
                        </div>
                      </div>
                      <Badge variant="outline" className="ml-4 bg-green-50">
                        합격
                      </Badge>
                    </div>
                  </SelectItem>
                ))
              )}
            </SelectContent>
          </Select>
        </FormField>

        {selectedOrderLot && selectedOrderLot.splitLots && selectedOrderLot.splitLots.length > 0 && (
          <FormField
            label="분할LOT"
            htmlFor="splitLotId"
            helpText="분할LOT가 있는 경우 선택하세요"
          >
            <Select 
              value={formData.splitLotId || "none"} 
              onValueChange={handleSplitLotChange}
            >
              <SelectTrigger id="splitLotId">
                <SelectValue placeholder="분할LOT 선택 (선택사항)" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">분할LOT 없음 (전체)</SelectItem>
                {selectedOrderLot.splitLots
                  .filter(split => split.inspectionStatus === 'passed')
                  .map(split => (
                    <SelectItem key={split.id} value={split.id}>
                      <div className="flex items-center justify-between w-full">
                        <div>
                          <div className="font-medium">{split.splitLotNo}</div>
                          <div className="text-xs text-muted-foreground">
                            수량: {split.quantity}개
                          </div>
                        </div>
                        <Badge variant="outline" className="ml-4 bg-green-50">
                          합격
                        </Badge>
                      </div>
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </FormField>
        )}

        <OrderLotInfo />
        <PaymentStatus />
      </FormSection>

      {/* 2. 출하정보 입력 */}
      <FormSection
        title="출하정보"
        description="출하 상세정보를 입력하세요"
        icon={Truck}
      >
        <FormFieldGrid columns={2}>
          <FormField
            label="출하예정일"
            required
            error={errors.shippingDate}
            htmlFor="shippingDate"
          >
            <Input
              id="shippingDate"
              type="date"
              value={formData.shippingDate}
              onChange={(e) => handleFieldChange("shippingDate", e.target.value)}
            />
          </FormField>

          <FormField
            label="출하수량"
            required
            error={errors.shippingQuantity}
            htmlFor="shippingQuantity"
            helpText={selectedOrderLot ? `최대 ${selectedSplitLot?.quantity || selectedOrderLot.remainingQuantity}개` : ''}
          >
            <Input
              id="shippingQuantity"
              type="number"
              min="0"
              max={selectedSplitLot?.quantity || selectedOrderLot?.remainingQuantity || 0}
              placeholder="수량 입력"
              value={formData.shippingQuantity || ""}
              onChange={(e) => handleFieldChange("shippingQuantity", parseInt(e.target.value) || 0)}
            />
          </FormField>
        </FormFieldGrid>

        <FormField
          label="납품장소"
          required
          error={errors.deliveryLocation}
          htmlFor="deliveryLocation"
        >
          <Input
            id="deliveryLocation"
            placeholder="납품장소 입력"
            value={formData.deliveryLocation}
            onChange={(e) => handleFieldChange("deliveryLocation", e.target.value)}
          />
        </FormField>

        <FormField
          label="비고"
          htmlFor="remarks"
        >
          <Textarea
            id="remarks"
            placeholder="추가 정보 입력"
            rows={3}
            value={formData.remarks || ""}
            onChange={(e) => handleFieldChange("remarks", e.target.value)}
          />
        </FormField>

        <ShippingConditionChecklist />
      </FormSection>
    </ResponsiveFormTemplate>
  );
}
