'use client';

/**
 * 출하 수정 페이지
 * API 연동 완료 (2025-12-26)
 * IntegratedDetailTemplate 마이그레이션 (2025-01-20)
 */

import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { CurrencyInput } from '@/components/ui/currency-input';
import { PhoneInput } from '@/components/ui/phone-input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { shipmentEditConfig } from './shipmentConfig';
import {
  getShipmentById,
  getLogisticsOptions,
  getVehicleTonnageOptions,
  updateShipment,
} from './actions';
import {
  SHIPMENT_STATUS_LABELS,
  SHIPMENT_STATUS_STYLES,
} from './types';
import type {
  ShipmentDetail,
  ShipmentEditFormData,
  ShipmentPriority,
  DeliveryMethod,
  LogisticsOption,
  VehicleTonnageOption,
} from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

// 고정 옵션 (클라이언트에서 관리)
const priorityOptions: { value: ShipmentPriority; label: string }[] = [
  { value: 'urgent', label: '긴급' },
  { value: 'normal', label: '일반' },
  { value: 'low', label: '낮음' },
];

const deliveryMethodOptions: { value: DeliveryMethod; label: string }[] = [
  { value: 'pickup', label: '상차 (물류업체)' },
  { value: 'direct', label: '직접배송 (자체)' },
  { value: 'logistics', label: '물류사' },
];

interface ShipmentEditProps {
  id: string;
}

export function ShipmentEdit({ id }: ShipmentEditProps) {
  const router = useRouter();

  // 상세 데이터 상태
  const [detail, setDetail] = useState<ShipmentDetail | null>(null);

  // 폼 상태
  const [formData, setFormData] = useState<ShipmentEditFormData>({
    scheduledDate: '',
    priority: 'normal',
    deliveryMethod: 'pickup',
    loadingManager: '',
    logisticsCompany: '',
    vehicleTonnage: '',
    vehicleNo: '',
    shippingCost: undefined,
    driverName: '',
    driverContact: '',
    expectedArrival: '',
    confirmedArrival: '',
    changeReason: '',
    remarks: '',
  });

  // API 옵션 데이터 상태
  const [logisticsOptions, setLogisticsOptions] = useState<LogisticsOption[]>([]);
  const [vehicleTonnageOptions, setVehicleTonnageOptions] = useState<VehicleTonnageOption[]>([]);

  // 로딩/에러 상태
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [validationErrors, setValidationErrors] = useState<string[]>([]);

  // 데이터 로드
  const loadData = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const [detailResult, logisticsResult, tonnageResult] = await Promise.all([
        getShipmentById(id),
        getLogisticsOptions(),
        getVehicleTonnageOptions(),
      ]);

      if (detailResult.success && detailResult.data) {
        const shipmentDetail = detailResult.data;
        setDetail(shipmentDetail);

        // 폼 초기값 설정
        setFormData({
          scheduledDate: shipmentDetail.scheduledDate,
          priority: shipmentDetail.priority,
          deliveryMethod: shipmentDetail.deliveryMethod,
          loadingManager: shipmentDetail.loadingManager || '',
          logisticsCompany: shipmentDetail.logisticsCompany || '',
          vehicleTonnage: shipmentDetail.vehicleTonnage || '',
          vehicleNo: shipmentDetail.vehicleNo || '',
          shippingCost: shipmentDetail.shippingCost,
          driverName: shipmentDetail.driverName || '',
          driverContact: shipmentDetail.driverContact || '',
          expectedArrival: '',
          confirmedArrival: '',
          changeReason: '',
          remarks: shipmentDetail.remarks || '',
        });
      } else {
        setError(detailResult.error || '출하 정보를 불러오는 데 실패했습니다.');
      }

      if (logisticsResult.success && logisticsResult.data) {
        setLogisticsOptions(logisticsResult.data);
      }

      if (tonnageResult.success && tonnageResult.data) {
        setVehicleTonnageOptions(tonnageResult.data);
      }
    } catch (err) {
      if (isNextRedirectError(err)) throw err;
      console.error('[ShipmentEdit] loadData error:', err);
      setError('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [id]);

  // 데이터 로드
  useEffect(() => {
    loadData();
  }, [loadData]);

  // 폼 입력 핸들러
  const handleInputChange = (field: keyof ShipmentEditFormData, value: string | number | undefined) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 입력 시 에러 클리어
    if (validationErrors.length > 0) {
      setValidationErrors([]);
    }
  };

  // 취소
  const handleCancel = useCallback(() => {
    router.push(`/ko/outbound/shipments/${id}?mode=view`);
  }, [router, id]);

  // validation 체크
  const validateForm = (): boolean => {
    const errors: string[] = [];

    // 필수 필드 체크
    if (!formData.scheduledDate) {
      errors.push('출고예정일은 필수 입력 항목입니다.');
    }
    if (!formData.priority) {
      errors.push('출고 우선순위는 필수 선택 항목입니다.');
    }
    if (!formData.deliveryMethod) {
      errors.push('배송방식은 필수 선택 항목입니다.');
    }
    if (!formData.changeReason.trim()) {
      errors.push('변경 사유는 필수 입력 항목입니다.');
    }

    setValidationErrors(errors);
    return errors.length === 0;
  };

  // 저장
  const handleSubmit = useCallback(async () => {
    // validation 체크
    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await updateShipment(id, formData);

      if (result.success) {
        router.push(`/ko/outbound/shipments/${id}?mode=view`);
      } else {
        setValidationErrors([result.error || '출하 수정에 실패했습니다.']);
      }
    } catch (err) {
      if (isNextRedirectError(err)) throw err;
      console.error('[ShipmentEdit] handleSubmit error:', err);
      setValidationErrors(['저장 중 오류가 발생했습니다.']);
    } finally {
      setIsSubmitting(false);
    }
  }, [id, formData, router]);

  // 동적 config (로트번호 + 상태 표시)
  // Note: IntegratedDetailTemplate이 edit 모드에서 '수정' 접미사 자동 추가
  const dynamicConfig = {
    ...shipmentEditConfig,
    title: detail?.lotNo ? `출하 (${detail.lotNo})` : '출하',
  };

  // 폼 컨텐츠 렌더링
  const renderFormContent = useCallback(() => {
    if (!detail) return null;

    return (
      <div className="space-y-6">
        {/* 상태 배지 */}
        <div className="flex items-center gap-2">
          <Badge className={`text-xs ${SHIPMENT_STATUS_STYLES[detail.status]}`}>
            {SHIPMENT_STATUS_LABELS[detail.status]}
          </Badge>
        </div>

        {/* Validation 에러 표시 */}
        {validationErrors.length > 0 && (
          <Alert className="bg-red-50 border-red-200">
            <AlertDescription className="text-red-900">
              <div className="flex items-start gap-2">
                <span className="text-lg">⚠️</span>
                <div className="flex-1">
                  <strong className="block mb-2">
                    입력 내용을 확인해주세요 ({validationErrors.length}개 오류)
                  </strong>
                  <ul className="space-y-1 text-sm">
                    {validationErrors.map((error, index) => (
                      <li key={index} className="flex items-start gap-1">
                        <span>•</span>
                        <span>{error}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {/* 기본 정보 (읽기 전용) */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              <div className="space-y-1">
                <Label className="text-muted-foreground">출고번호</Label>
                <div className="font-medium">{detail.shipmentNo}</div>
              </div>
              <div className="space-y-1">
                <Label className="text-muted-foreground">로트번호</Label>
                <div className="font-medium">{detail.lotNo}</div>
              </div>
              <div className="space-y-1">
                <Label className="text-muted-foreground">발주처</Label>
                <div className="font-medium">{detail.customerName}</div>
              </div>
              <div className="space-y-1">
                <Label className="text-muted-foreground">현장명</Label>
                <div className="font-medium">{detail.siteName}</div>
              </div>
              <div className="space-y-1 md:col-span-4">
                <Label className="text-muted-foreground">배송주소</Label>
                <div className="font-medium">{detail.deliveryAddress}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 출고 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">출고 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>출고예정일 *</Label>
                <Input
                  type="date"
                  value={formData.scheduledDate}
                  onChange={(e) => handleInputChange('scheduledDate', e.target.value)}
                  disabled={isSubmitting}
                />
              </div>
              <div className="space-y-2">
                <Label>출고 우선순위 *</Label>
                <Select
                  value={formData.priority}
                  onValueChange={(value) => handleInputChange('priority', value as ShipmentPriority)}
                  disabled={isSubmitting}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="우선순위 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {priorityOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>배송방식 *</Label>
                <Select
                  value={formData.deliveryMethod}
                  onValueChange={(value) => handleInputChange('deliveryMethod', value as DeliveryMethod)}
                  disabled={isSubmitting}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="배송방식 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {deliveryMethodOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>상차담당자</Label>
                <Input
                  value={formData.loadingManager || ''}
                  onChange={(e) => handleInputChange('loadingManager', e.target.value)}
                  placeholder="상차담당자명"
                  disabled={isSubmitting}
                />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>물류사</Label>
                <Select
                  value={formData.logisticsCompany || ''}
                  onValueChange={(value) => handleInputChange('logisticsCompany', value)}
                  disabled={isSubmitting}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {logisticsOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>차량 톤수</Label>
                <Select
                  value={formData.vehicleTonnage || ''}
                  onValueChange={(value) => handleInputChange('vehicleTonnage', value)}
                  disabled={isSubmitting}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {vehicleTonnageOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 배차 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">배차 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>차량번호</Label>
                <Input
                  value={formData.vehicleNo || ''}
                  onChange={(e) => handleInputChange('vehicleNo', e.target.value)}
                  placeholder="예: 12가 3456"
                  disabled={isSubmitting}
                />
              </div>
              <div className="space-y-2">
                <Label>운송비</Label>
                <CurrencyInput
                  value={formData.shippingCost || 0}
                  onChange={(value) => handleInputChange('shippingCost', value ?? undefined)}
                  placeholder="0"
                  disabled={isSubmitting}
                />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>운전자명</Label>
                <Input
                  value={formData.driverName || ''}
                  onChange={(e) => handleInputChange('driverName', e.target.value)}
                  placeholder="운전자명"
                  disabled={isSubmitting}
                />
              </div>
              <div className="space-y-2">
                <Label>운전자 연락처</Label>
                <PhoneInput
                  value={formData.driverContact || ''}
                  onChange={(value) => handleInputChange('driverContact', value)}
                  placeholder="010-0000-0000"
                  disabled={isSubmitting}
                />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>입차예정시간</Label>
                <Input
                  type="datetime-local"
                  value={formData.expectedArrival || ''}
                  onChange={(e) => handleInputChange('expectedArrival', e.target.value)}
                  disabled={isSubmitting}
                />
              </div>
              <div className="space-y-2">
                <Label>입차확정시간</Label>
                <Input
                  type="datetime-local"
                  value={formData.confirmedArrival || ''}
                  onChange={(e) => handleInputChange('confirmedArrival', e.target.value)}
                  disabled={isSubmitting}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 변경 사유 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">변경 사유</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label>변경 사유 *</Label>
              <Input
                value={formData.changeReason}
                onChange={(e) => handleInputChange('changeReason', e.target.value)}
                placeholder="변경 사유를 입력하세요 (예: 고객 요청, 물류사 일정 조율 등)"
                disabled={isSubmitting}
              />
            </div>
            <div className="space-y-2">
              <Label>비고</Label>
              <Textarea
                value={formData.remarks || ''}
                onChange={(e) => handleInputChange('remarks', e.target.value)}
                placeholder="특이사항 입력"
                rows={4}
                disabled={isSubmitting}
              />
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }, [detail, formData, validationErrors, isSubmitting, logisticsOptions, vehicleTonnageOptions]);

  // 에러 상태 표시
  if (error && !isLoading) {
    return (
      <IntegratedDetailTemplate
        config={dynamicConfig}
        mode="edit"
        isLoading={false}
        onBack={handleCancel}
        renderForm={() => (
          <Alert className="bg-red-50 border-red-200">
            <AlertDescription className="text-red-900">
              {error || '출하 정보를 찾을 수 없습니다.'}
            </AlertDescription>
          </Alert>
        )}
      />
    );
  }

  return (
    <IntegratedDetailTemplate
      config={dynamicConfig}
      mode="edit"
      isLoading={isLoading}
      isSubmitting={isSubmitting}
      onBack={handleCancel}
      onCancel={handleCancel}
      onSubmit={handleSubmit}
      renderForm={renderFormContent}
    />
  );
}
