'use client';

import { useState, useEffect, useCallback } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { DatePicker } from '@/components/ui/date-picker';
import { Loader2 } from 'lucide-react';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  type CorporateVehicle,
  type VehicleFormData,
  type OwnershipType,
  EMPTY_VEHICLE_FORM,
  VEHICLE_TYPES,
} from '../types';
import {
  createCorporateVehicle,
  updateCorporateVehicle,
  deleteCorporateVehicle,
} from './actions';

interface VehicleFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: 'create' | 'edit';
  vehicle?: CorporateVehicle | null;
  onSuccess: () => void;
}

export function VehicleFormDialog({
  open,
  onOpenChange,
  mode,
  vehicle,
  onSuccess,
}: VehicleFormDialogProps) {
  const [form, setForm] = useState<VehicleFormData>(EMPTY_VEHICLE_FORM);
  const [isSaving, setIsSaving] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const isEdit = mode === 'edit';
  const isCorporate = form.ownershipType !== 'rent' && form.ownershipType !== 'lease';

  useEffect(() => {
    if (!open) return;
    if (isEdit && vehicle) {
      setForm({
        plateNumber: vehicle.plateNumber,
        vehicleType: vehicle.vehicleType || '',
        ownershipType: vehicle.ownershipType || '',
        model: vehicle.model,
        year: vehicle.year ? String(vehicle.year) : '',
        purchaseDate: vehicle.purchaseDate || '',
        contractDate: vehicle.contractDate || '',
        rentCompany: vehicle.rentCompany || '',
        rentPeriod: vehicle.rentPeriod || '',
        purchasePrice: vehicle.purchasePrice ? String(vehicle.purchasePrice) : '',
        monthlyRent: vehicle.monthlyRent ? String(vehicle.monthlyRent) : '',
        monthlyRentTax: vehicle.monthlyRentTax ? String(vehicle.monthlyRentTax) : '',
        rentCompanyTel: vehicle.rentCompanyTel || '',
        agreedMileage: vehicle.agreedMileage || '',
        vehiclePrice: vehicle.vehiclePrice ? String(vehicle.vehiclePrice) : '',
        residualValue: vehicle.residualValue ? String(vehicle.residualValue) : '',
        deposit: vehicle.deposit ? String(vehicle.deposit) : '',
        mileage: vehicle.mileage ? String(vehicle.mileage) : '',
        insuranceCompany: vehicle.insuranceCompany || '',
        insuranceCompanyTel: vehicle.insuranceCompanyTel || '',
        driver: vehicle.driver || '',
        status: vehicle.status || '',
        memo: vehicle.memo || '',
      });
    } else {
      setForm(EMPTY_VEHICLE_FORM);
    }
  }, [open, isEdit, vehicle]);

  const updateField = useCallback(
    <K extends keyof VehicleFormData>(key: K, value: VehicleFormData[K]) => {
      setForm((prev) => ({ ...prev, [key]: value }));
    },
    []
  );

  const handleSubmit = async () => {
    if (!form.plateNumber || !form.ownershipType || !form.model) {
      toast.error('필수 항목을 입력해주세요.');
      return;
    }
    setIsSaving(true);
    try {
      const result = isEdit && vehicle
        ? await updateCorporateVehicle(vehicle.id, form)
        : await createCorporateVehicle(form);
      if (result.success) {
        toast.success(isEdit ? '차량이 수정되었습니다.' : '차량이 등록되었습니다.');
        onOpenChange(false);
        onSuccess();
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!vehicle) return;
    setIsDeleting(true);
    try {
      const result = await deleteCorporateVehicle(vehicle.id);
      if (result.success) {
        toast.success('차량이 삭제되었습니다.');
        setDeleteOpen(false);
        onOpenChange(false);
        onSuccess();
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } catch {
      toast.error('삭제 중 오류가 발생했습니다.');
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isEdit ? '차량 수정' : '차량 등록'}</DialogTitle>
          </DialogHeader>

          <div className="space-y-4 py-2">
            {/* Row 1: 차량번호, 종류, 구분 */}
            <div className="grid grid-cols-3 gap-3">
              <div className="space-y-1.5">
                <Label>차량번호 <span className="text-red-500">*</span></Label>
                <Input
                  value={form.plateNumber}
                  onChange={(e) => updateField('plateNumber', e.target.value)}
                  placeholder="12가 3456"
                />
              </div>
              <div className="space-y-1.5">
                <Label>종류</Label>
                <Select
                  key={`vt-${form.vehicleType}`}
                  value={form.vehicleType}
                  onValueChange={(v) => updateField('vehicleType', v as VehicleFormData['vehicleType'])}
                >
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    {VEHICLE_TYPES.map((t) => (
                      <SelectItem key={t} value={t}>{t}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label>구분 <span className="text-red-500">*</span></Label>
                <Select
                  key={`ot-${form.ownershipType}`}
                  value={form.ownershipType}
                  onValueChange={(v) => updateField('ownershipType', v as OwnershipType)}
                >
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="corporate">법인차량</SelectItem>
                    <SelectItem value="rent">렌트차량</SelectItem>
                    <SelectItem value="lease">리스차량</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Row 2: 모델 */}
            <div className="space-y-1.5">
              <Label>모델 <span className="text-red-500">*</span></Label>
              <Input
                value={form.model}
                onChange={(e) => updateField('model', e.target.value)}
                placeholder="차량 모델명"
              />
            </div>

            {/* Row 3: 연식, 취득일/계약일자 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>연식</Label>
                <Input
                  type="number"
                  value={form.year}
                  onChange={(e) => updateField('year', e.target.value)}
                  placeholder="2026"
                />
              </div>
              <div className="space-y-1.5">
                <Label>{isCorporate ? '취득일' : '계약일자'}</Label>
                {isCorporate ? (
                  <DatePicker
                    value={form.purchaseDate}
                    onChange={(v) => updateField('purchaseDate', v)}
                    placeholder="연도. 월. 일."
                  />
                ) : (
                  <DatePicker
                    value={form.contractDate}
                    onChange={(v) => updateField('contractDate', v)}
                    placeholder="연도. 월. 일."
                  />
                )}
              </div>
            </div>

            {/* Row 4: 구매처/렌트회사명, 계약기간/렌트기간 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>{isCorporate ? '구매처' : '렌트회사명'}</Label>
                <Input
                  value={form.rentCompany}
                  onChange={(e) => updateField('rentCompany', e.target.value)}
                  placeholder={isCorporate ? '회사명' : '렌트회사명'}
                />
              </div>
              <div className="space-y-1.5">
                <Label>{isCorporate ? '계약기간' : '렌트기간'}</Label>
                <Input
                  value={form.rentPeriod}
                  onChange={(e) => updateField('rentPeriod', e.target.value)}
                  placeholder="예: 36개월"
                />
              </div>
            </div>

            {/* Row 5: 취득가(공급가)/월렌트료(공급가), 세액 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>{isCorporate ? '취득가 (공급가)' : '월 렌트료 (공급가)'}</Label>
                {isCorporate ? (
                  <Input
                    type="number"
                    value={form.purchasePrice}
                    onChange={(e) => updateField('purchasePrice', e.target.value)}
                    placeholder="0"
                  />
                ) : (
                  <Input
                    type="number"
                    value={form.monthlyRent}
                    onChange={(e) => updateField('monthlyRent', e.target.value)}
                    placeholder="0"
                  />
                )}
              </div>
              <div className="space-y-1.5">
                <Label>세액</Label>
                <Input
                  type="number"
                  value={form.monthlyRentTax}
                  onChange={(e) => updateField('monthlyRentTax', e.target.value)}
                  placeholder="0"
                />
              </div>
            </div>

            {/* Row 6: 회사 연락처, 약정운행거리 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>회사 연락처</Label>
                <Input
                  value={form.rentCompanyTel}
                  onChange={(e) => updateField('rentCompanyTel', e.target.value)}
                  placeholder="연락처"
                />
              </div>
              <div className="space-y-1.5">
                <Label>약정운행거리</Label>
                <Input
                  value={form.agreedMileage}
                  onChange={(e) => updateField('agreedMileage', e.target.value)}
                  placeholder="km"
                />
              </div>
            </div>

            {/* Row 7: 차량가격, 추정잔존가액 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>차량가격</Label>
                <Input
                  type="number"
                  value={form.vehiclePrice}
                  onChange={(e) => updateField('vehiclePrice', e.target.value)}
                  placeholder="0"
                />
              </div>
              <div className="space-y-1.5">
                <Label>추정잔존가액</Label>
                <Input
                  type="number"
                  value={form.residualValue}
                  onChange={(e) => updateField('residualValue', e.target.value)}
                  placeholder="0"
                />
              </div>
            </div>

            {/* Row 8: 보증금, 최초 주행거리 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>보증금</Label>
                <Input
                  type="number"
                  value={form.deposit}
                  onChange={(e) => updateField('deposit', e.target.value)}
                  placeholder="0"
                />
              </div>
              <div className="space-y-1.5">
                <Label>최초 주행거리(km)</Label>
                <Input
                  type="number"
                  value={form.mileage}
                  onChange={(e) => updateField('mileage', e.target.value)}
                  placeholder="0"
                />
              </div>
            </div>

            {/* Row 9: 보험사명, 보험사 연락처 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>보험사명</Label>
                <Input
                  value={form.insuranceCompany}
                  onChange={(e) => updateField('insuranceCompany', e.target.value)}
                  placeholder="보험사명"
                />
              </div>
              <div className="space-y-1.5">
                <Label>보험사 연락처</Label>
                <Input
                  value={form.insuranceCompanyTel}
                  onChange={(e) => updateField('insuranceCompanyTel', e.target.value)}
                  placeholder="연락처"
                />
              </div>
            </div>

            {/* Row 10: 운전자, 상태 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>운전자</Label>
                <Input
                  value={form.driver}
                  onChange={(e) => updateField('driver', e.target.value)}
                  placeholder="운전자명"
                />
              </div>
              <div className="space-y-1.5">
                <Label>상태</Label>
                <Select
                  key={`st-${form.status}`}
                  value={form.status}
                  onValueChange={(v) => updateField('status', v as VehicleFormData['status'])}
                >
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">운행중</SelectItem>
                    <SelectItem value="maintenance">정비중</SelectItem>
                    <SelectItem value="disposed">처분</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Row 11: 메모 */}
            <div className="space-y-1.5">
              <Label>메모</Label>
              <Textarea
                value={form.memo}
                onChange={(e) => updateField('memo', e.target.value)}
                placeholder="메모"
                rows={2}
              />
            </div>
          </div>

          {/* 버튼 */}
          <div className="flex items-center gap-2 pt-2">
            {isEdit && (
              <Button
                variant="destructive"
                size="sm"
                onClick={() => setDeleteOpen(true)}
              >
                삭제
              </Button>
            )}
            <div className="flex-1" />
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              취소
            </Button>
            <Button onClick={handleSubmit} disabled={isSaving}>
              {isSaving && <Loader2 className="h-4 w-4 mr-1 animate-spin" />}
              {isEdit ? '저장' : '등록'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      <DeleteConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        description="이 차량을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다."
        loading={isDeleting}
        onConfirm={handleDelete}
      />
    </>
  );
}
