'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 { ArrowUpDown, Loader2 } from 'lucide-react';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  type VehicleLog,
  type VehicleLogFormData,
  type VehicleDropdownItem,
  type TripType,
  type LocationType,
  EMPTY_LOG_FORM,
  TRIP_TYPE_LABELS,
  LOCATION_TYPE_LABELS,
  NOTE_PRESETS,
} from '../types';
import {
  createVehicleLog,
  updateVehicleLog,
  deleteVehicleLog,
} from './actions';

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

export function VehicleLogFormDialog({
  open,
  onOpenChange,
  mode,
  log,
  vehicles,
  onSuccess,
}: VehicleLogFormDialogProps) {
  const [form, setForm] = useState<VehicleLogFormData>(EMPTY_LOG_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 && log) {
      setForm({
        vehicleId: String(log.vehicleId),
        logDate: log.logDate,
        department: log.department || '',
        driverName: log.driverName,
        tripType: log.tripType,
        departureType: log.departureType,
        departureName: log.departureName || '',
        departureAddress: log.departureAddress || '',
        arrivalType: log.arrivalType,
        arrivalName: log.arrivalName || '',
        arrivalAddress: log.arrivalAddress || '',
        distanceKm: log.distanceKm ? String(log.distanceKm) : '',
        note: log.note || '',
      });
    } else {
      setForm({
        ...EMPTY_LOG_FORM,
        logDate: new Date().toISOString().slice(0, 10),
      });
    }
  }, [open, isEdit, log]);

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

  // 출발↔도착 교환
  const handleSwapLocations = useCallback(() => {
    setForm((prev) => {
      // trip_type 자동 전환
      let newTripType = prev.tripType;
      if (prev.tripType === 'commute_to') newTripType = 'commute_from';
      else if (prev.tripType === 'commute_from') newTripType = 'commute_to';

      return {
        ...prev,
        tripType: newTripType,
        departureType: prev.arrivalType,
        departureName: prev.arrivalName,
        departureAddress: prev.arrivalAddress,
        arrivalType: prev.departureType,
        arrivalName: prev.departureName,
        arrivalAddress: prev.departureAddress,
      };
    });
  }, []);

  // 비고 프리셋 삽입
  const handleNotePreset = useCallback((preset: string) => {
    setForm((prev) => ({
      ...prev,
      note: prev.note ? `${prev.note} ${preset}` : preset,
    }));
  }, []);

  const handleSubmit = async () => {
    if (!form.vehicleId || !form.tripType || !form.driverName) {
      toast.error('필수 항목을 입력해주세요.');
      return;
    }
    setIsSaving(true);
    try {
      const result = isEdit && log
        ? await updateVehicleLog(log.id, form)
        : await createVehicleLog(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 (!log) return;
    setIsDeleting(true);
    try {
      const result = await deleteVehicleLog(log.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>
            <div className="flex items-center gap-2">
              <DialogTitle>{isEdit ? '운행기록 수정' : '운행기록 등록'}</DialogTitle>
              <Button
                variant="outline"
                size="sm"
                onClick={handleSwapLocations}
                className="text-xs"
              >
                <ArrowUpDown className="h-3.5 w-3.5 mr-1" />
                출발↔도착
              </Button>
            </div>
          </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>
                <DatePicker
                  value={form.logDate}
                  onChange={(v) => updateField('logDate', v)}
                  placeholder="날짜 선택"
                />
              </div>
              <div className="space-y-1.5">
                <Label>차량 <span className="text-red-500">*</span></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>
              <div className="space-y-1.5">
                <Label>구분 <span className="text-red-500">*</span></Label>
                <Select
                  key={`tt-${form.tripType}`}
                  value={form.tripType}
                  onValueChange={(v) => updateField('tripType', v as TripType)}
                >
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    {(Object.entries(TRIP_TYPE_LABELS) as [TripType, string][]).map(([key, label]) => (
                      <SelectItem key={key} value={key}>{label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Row 2: 부서, 운전자, 주행거리 */}
            <div className="grid grid-cols-3 gap-3">
              <div className="space-y-1.5">
                <Label>부서</Label>
                <Input
                  value={form.department}
                  onChange={(e) => updateField('department', e.target.value)}
                  placeholder="부서"
                />
              </div>
              <div className="space-y-1.5">
                <Label>운전자 <span className="text-red-500">*</span></Label>
                <Input
                  value={form.driverName}
                  onChange={(e) => updateField('driverName', e.target.value)}
                  placeholder="운전자명"
                />
              </div>
              <div className="space-y-1.5">
                <Label>주행거리 (km) <span className="text-red-500">*</span></Label>
                <Input
                  type="number"
                  value={form.distanceKm}
                  onChange={(e) => updateField('distanceKm', e.target.value)}
                  placeholder="0"
                />
              </div>
            </div>

            {/* 출발지 */}
            <div className="space-y-2">
              <div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
                <span className="w-2 h-2 rounded-full bg-green-500" />
                출발지
              </div>
              <div className="grid grid-cols-3 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs">분류</Label>
                  <Select
                    key={`dt-${form.departureType}`}
                    value={form.departureType as string}
                    onValueChange={(v) => updateField('departureType', v as LocationType)}
                  >
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      {(Object.entries(LOCATION_TYPE_LABELS) as [LocationType, string][]).map(([key, label]) => (
                        <SelectItem key={key} value={key}>{label}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">출발지명</Label>
                  <Input
                    value={form.departureName}
                    onChange={(e) => updateField('departureName', e.target.value)}
                    placeholder="출발지명"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">주소</Label>
                  <Input
                    value={form.departureAddress}
                    onChange={(e) => updateField('departureAddress', e.target.value)}
                    placeholder="주소"
                  />
                </div>
              </div>
            </div>

            {/* 도착지 */}
            <div className="space-y-2">
              <div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
                <span className="w-2 h-2 rounded-full bg-red-500" />
                도착지
              </div>
              <div className="grid grid-cols-3 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs">분류</Label>
                  <Select
                    key={`at-${form.arrivalType}`}
                    value={form.arrivalType as string}
                    onValueChange={(v) => updateField('arrivalType', v as LocationType)}
                  >
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      {(Object.entries(LOCATION_TYPE_LABELS) as [LocationType, string][]).map(([key, label]) => (
                        <SelectItem key={key} value={key}>{label}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">도착지명</Label>
                  <Input
                    value={form.arrivalName}
                    onChange={(e) => updateField('arrivalName', e.target.value)}
                    placeholder="도착지명"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">주소</Label>
                  <Input
                    value={form.arrivalAddress}
                    onChange={(e) => updateField('arrivalAddress', e.target.value)}
                    placeholder="주소"
                  />
                </div>
              </div>
            </div>

            {/* 비고 */}
            <div className="space-y-2">
              <Label>비고</Label>
              <div className="flex flex-wrap gap-1.5 mb-2">
                {NOTE_PRESETS.map((preset) => (
                  <Button
                    key={preset}
                    variant="outline"
                    size="sm"
                    className="text-xs h-7"
                    onClick={() => handleNotePreset(preset)}
                  >
                    {preset}
                  </Button>
                ))}
              </div>
              <Textarea
                value={form.note}
                onChange={(e) => updateField('note', 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}
              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}
      />
    </>
  );
}
