'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 { CurrencyInput } from '@/components/ui/currency-input';
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 VehicleMaintenance,
  type MaintenanceFormData,
  type MaintenanceCategory,
  type VehicleDropdownItem,
  EMPTY_MAINTENANCE_FORM,
  MAINTENANCE_CATEGORIES,
} from '../types';
import {
  createVehicleMaintenance,
  updateVehicleMaintenance,
  deleteVehicleMaintenance,
} from './actions';

interface MaintenanceFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: 'create' | 'edit';
  maintenance?: VehicleMaintenance | null;
  vehicles: VehicleDropdownItem[];
  onSuccess: () => void;
}

export function MaintenanceFormDialog({
  open,
  onOpenChange,
  mode,
  maintenance,
  vehicles,
  onSuccess,
}: MaintenanceFormDialogProps) {
  const [form, setForm] = useState<MaintenanceFormData>(EMPTY_MAINTENANCE_FORM);
  const [isSaving, setIsSaving] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const isEdit = mode === 'edit';

  useEffect(() => {
    if (!open) return;
    if (isEdit && maintenance) {
      setForm({
        vehicleId: String(maintenance.vehicleId),
        date: maintenance.date,
        category: maintenance.category,
        description: maintenance.description || '',
        amount: maintenance.amount ? String(maintenance.amount) : '',
        mileage: maintenance.mileage ? String(maintenance.mileage) : '',
        vendor: maintenance.vendor || '',
        memo: maintenance.memo || '',
      });
    } else {
      setForm({
        ...EMPTY_MAINTENANCE_FORM,
        date: new Date().toISOString().slice(0, 10),
      });
    }
  }, [open, isEdit, maintenance]);

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

  const handleSubmit = async () => {
    if (!form.vehicleId || !form.category || !form.description) {
      toast.error('필수 항목을 입력해주세요.');
      return;
    }
    setIsSaving(true);
    try {
      const result = isEdit && maintenance
        ? await updateVehicleMaintenance(maintenance.id, form)
        : await createVehicleMaintenance(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 (!maintenance) return;
    setIsDeleting(true);
    try {
      const result = await deleteVehicleMaintenance(maintenance.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-2 gap-3">
              <div className="space-y-1.5">
                <Label>날짜 <span className="text-red-500">*</span></Label>
                <DatePicker
                  value={form.date}
                  onChange={(v) => updateField('date', v)}
                  placeholder="날짜 선택"
                />
              </div>
              <div className="space-y-1.5">
                <Label>구분</Label>
                <Select
                  key={`cat-${form.category}`}
                  value={form.category as string}
                  onValueChange={(v) => updateField('category', v as MaintenanceCategory)}
                >
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    {MAINTENANCE_CATEGORIES.map((cat) => (
                      <SelectItem key={cat} value={cat}>{cat}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Row 2: 차량 */}
            <div className="space-y-1.5">
              <Label>차량</Label>
              <Select
                key={`v-${form.vehicleId}`}
                value={form.vehicleId}
                onValueChange={(v) => updateField('vehicleId', v)}
              >
                <SelectTrigger><SelectValue placeholder="차량 선택" /></SelectTrigger>
                <SelectContent>
                  {vehicles.map((v) => (
                    <SelectItem key={v.id} value={String(v.id)}>
                      {v.plateNumber} ({v.model})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Row 3: 내용 */}
            <div className="space-y-1.5">
              <Label>내용 <span className="text-red-500">*</span></Label>
              <Input
                value={form.description}
                onChange={(e) => updateField('description', e.target.value)}
                placeholder="내용"
              />
            </div>

            {/* Row 4: 금액, 주행거리 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>금액 <span className="text-red-500">*</span></Label>
                <CurrencyInput
                  value={form.amount ? Number(form.amount) : undefined}
                  onChange={(v) => updateField('amount', v ? String(v) : '')}
                  showCurrency={false}
                />
              </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 5: 업체, 메모 */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>업체</Label>
                <Input
                  value={form.vendor}
                  onChange={(e) => updateField('vendor', e.target.value)}
                  placeholder="업체명"
                />
              </div>
              <div className="space-y-1.5">
                <Label>메모</Label>
                <Input
                  value={form.memo}
                  onChange={(e) => updateField('memo', e.target.value)}
                  placeholder="메모"
                />
              </div>
            </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}
              className={isEdit ? '' : 'bg-green-600 hover:bg-green-700'}
            >
              {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}
      />
    </>
  );
}
