'use client';

/**
 * 출하 수정 페이지
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Truck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
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 { PageLayout } from '@/components/organisms/PageLayout';
import {
  mockShipmentDetail,
  mockLogisticsOptions,
  mockVehicleTonnageOptions,
  priorityOptions,
  deliveryMethodOptions,
} from './mockData';
import type { ShipmentEditFormData, ShipmentPriority, DeliveryMethod } from './types';

interface ShipmentEditProps {
  id: string;
}

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

  // Mock 데이터에서 초기값 설정 (실제로는 API에서 조회)
  const detail = mockShipmentDetail;

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

  // validation 에러 상태
  const [validationErrors, setValidationErrors] = useState<string[]>([]);

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

  // 취소
  const handleCancel = () => {
    router.push(`/ko/outbound/shipments/${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 = () => {
    // validation 체크
    if (!validateForm()) {
      return;
    }

    // TODO: API 호출
    console.log('Submit:', formData);
    router.push(`/ko/outbound/shipments/${id}`);
  };

  return (
    <PageLayout>
      <div className="space-y-6">
        {/* 헤더 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="icon"
              onClick={handleCancel}
            >
              <ArrowLeft className="w-5 h-5" />
            </Button>
            <Truck className="w-6 h-6" />
            <h1 className="text-xl font-semibold">출고 수정</h1>
            <span className="text-sm text-muted-foreground">{detail.lotNo}</span>
            <Badge variant="outline" className="bg-yellow-100 text-yellow-800">
              출하보류
            </Badge>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleCancel}>
              취소
            </Button>
            <Button onClick={handleSubmit}>
              저장
            </Button>
          </div>
        </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)}
                />
              </div>
              <div className="space-y-2">
                <Label>출고 우선순위 *</Label>
                <Select
                  value={formData.priority}
                  onValueChange={(value) => handleInputChange('priority', value as ShipmentPriority)}
                >
                  <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)}
                >
                  <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="상차담당자명"
                />
              </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)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {mockLogisticsOptions.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)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {mockVehicleTonnageOptions.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"
                />
              </div>
              <div className="space-y-2">
                <Label>운송비</Label>
                <Input
                  type="number"
                  value={formData.shippingCost || ''}
                  onChange={(e) => handleInputChange('shippingCost', parseInt(e.target.value) || undefined)}
                  placeholder="0"
                />
              </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="운전자명"
                />
              </div>
              <div className="space-y-2">
                <Label>운전자 연락처</Label>
                <Input
                  value={formData.driverContact || ''}
                  onChange={(e) => handleInputChange('driverContact', e.target.value)}
                  placeholder="010-0000-0000"
                />
              </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)}
                />
              </div>
              <div className="space-y-2">
                <Label>입차확정시간</Label>
                <Input
                  type="datetime-local"
                  value={formData.confirmedArrival || ''}
                  onChange={(e) => handleInputChange('confirmedArrival', e.target.value)}
                />
              </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="변경 사유를 입력하세요 (예: 고객 요청, 물류사 일정 조율 등)"
              />
            </div>
            <div className="space-y-2">
              <Label>비고</Label>
              <Textarea
                value={formData.remarks || ''}
                onChange={(e) => handleInputChange('remarks', e.target.value)}
                placeholder="특이사항 입력"
                rows={4}
              />
            </div>
          </CardContent>
        </Card>
      </div>
    </PageLayout>
  );
}