'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 { 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 {
  mockLotOptions,
  mockLogisticsOptions,
  mockVehicleTonnageOptions,
  priorityOptions,
  deliveryMethodOptions,
} from './mockData';
import type { ShipmentCreateFormData, ShipmentPriority, DeliveryMethod } from './types';

export function ShipmentCreate() {
  const router = useRouter();

  // 폼 상태
  const [formData, setFormData] = useState<ShipmentCreateFormData>({
    lotNo: '',
    scheduledDate: new Date().toISOString().split('T')[0],
    priority: 'normal',
    deliveryMethod: 'pickup',
    logisticsCompany: '',
    vehicleTonnage: '',
    loadingTime: '',
    loadingManager: '',
    remarks: '',
  });

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

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

  // 취소
  const handleCancel = () => {
    router.push('/ko/outbound/shipments');
  };

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

    // 필수 필드 체크
    if (!formData.lotNo) {
      errors.push('로트번호는 필수 선택 항목입니다.');
    }
    if (!formData.scheduledDate) {
      errors.push('출고예정일은 필수 입력 항목입니다.');
    }
    if (!formData.priority) {
      errors.push('출고 우선순위는 필수 선택 항목입니다.');
    }
    if (!formData.deliveryMethod) {
      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');
  };

  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>
          </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="space-y-2">
              <Label>로트번호 *</Label>
              <Select
                value={formData.lotNo}
                onValueChange={(value) => handleInputChange('lotNo', value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="로트 선택" />
                </SelectTrigger>
                <SelectContent>
                  {mockLotOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label} ({option.customerName} - {option.siteName})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </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="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>

            {/* 상차 (물류업체) - 배송방식이 상차 또는 물류사일 때 표시 */}
            {(formData.deliveryMethod === 'pickup' || formData.deliveryMethod === 'logistics') && (
              <Card className="bg-muted/30">
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium">상차 (물류업체)</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>
                      <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>
                  <div className="space-y-2">
                    <Label>상차시간 (입차예정)</Label>
                    <Input
                      type="datetime-local"
                      value={formData.loadingTime || ''}
                      onChange={(e) => handleInputChange('loadingTime', e.target.value)}
                      placeholder="연도. 월. 일. -- --:--"
                    />
                    <p className="text-sm text-muted-foreground">
                      물류업체와 입차시간 확정 후 입력하세요.
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}

            <div className="space-y-2">
              <Label>상차담당자</Label>
              <Input
                value={formData.loadingManager || ''}
                onChange={(e) => handleInputChange('loadingManager', 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>
  );
}