'use client';

import { useState, useEffect, useCallback } from 'react';
import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { FormField } from '@/components/molecules/FormField';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { toast } from 'sonner';
import { calendarScheduleFormSchema, SCHEDULE_TYPE_OPTIONS } from './types';
import type { CalendarSchedule, CalendarScheduleFormData, CalendarScheduleType } from './types';
import { createCalendarSchedule, updateCalendarSchedule, deleteCalendarSchedule } from './actions';

interface CalendarDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: 'create' | 'edit';
  schedule?: CalendarSchedule | null;
  defaultDate?: string;
  onSuccess: () => void;
}

const EMPTY_FORM: CalendarScheduleFormData = {
  name: '',
  type: 'publicHoliday',
  startDate: '',
  endDate: '',
  isRecurring: false,
  memo: '',
};

export function CalendarDetailDialog({
  open,
  onOpenChange,
  mode,
  schedule,
  defaultDate,
  onSuccess,
}: CalendarDetailDialogProps) {
  const [formData, setFormData] = useState<CalendarScheduleFormData>(EMPTY_FORM);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    if (!open) return;
    if (mode === 'edit' && schedule) {
      setFormData({
        name: schedule.name,
        type: schedule.type,
        startDate: schedule.startDate,
        endDate: schedule.endDate,
        isRecurring: schedule.isRecurring,
        memo: schedule.memo,
      });
    } else {
      setFormData({
        ...EMPTY_FORM,
        startDate: defaultDate || '',
        endDate: defaultDate || '',
      });
    }
    setErrors({});
  }, [open, mode, schedule, defaultDate]);

  const handleChange = useCallback((field: keyof CalendarScheduleFormData, value: string | boolean) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    setErrors((prev) => {
      if (!prev[field]) return prev;
      const next = { ...prev };
      delete next[field];
      return next;
    });
  }, []);

  const handleSubmit = async () => {
    const validation = calendarScheduleFormSchema.safeParse(formData);
    if (!validation.success) {
      const fieldErrors: Record<string, string> = {};
      for (const issue of validation.error.issues) {
        const field = String(issue.path[0]);
        if (!fieldErrors[field]) fieldErrors[field] = issue.message;
      }
      setErrors(fieldErrors);
      toast.error(validation.error.issues[0]?.message || '입력값을 확인해주세요.');
      return;
    }

    setIsSaving(true);
    try {
      const result = mode === 'create'
        ? await createCalendarSchedule(formData)
        : schedule?.id
          ? await updateCalendarSchedule(schedule.id, formData)
          : null;

      if (!result) return;

      if (result.success) {
        toast.success(mode === 'create' ? '일정이 등록되었습니다.' : '일정이 수정되었습니다.');
        onOpenChange(false);
        onSuccess();
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  };

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

  const typeOptions = SCHEDULE_TYPE_OPTIONS
    .filter((o) => o.value !== 'all')
    .map((o) => ({ value: o.value, label: o.label }));

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>{mode === 'create' ? '달력 일정 등록' : '달력 일정 수정'}</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <FormField
            label="일정명"
            required
            value={formData.name}
            onChange={(v) => handleChange('name', v)}
            placeholder="일정명을 입력하세요"
            error={errors.name}
          />

          <FormField
            label="유형"
            required
            type="select"
            value={formData.type}
            onChange={(v) => handleChange('type', v as CalendarScheduleType)}
            options={typeOptions}
            selectPlaceholder="유형 선택"
            error={errors.type}
          />

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>
                시작일 <span className="text-destructive">*</span>
              </Label>
              <DatePicker
                value={formData.startDate}
                onChange={(v) => handleChange('startDate', v)}
                placeholder="시작일"
              />
              {errors.startDate && (
                <p className="text-sm text-destructive">{errors.startDate}</p>
              )}
            </div>
            <div className="space-y-2">
              <Label>
                종료일 <span className="text-destructive">*</span>
              </Label>
              <DatePicker
                value={formData.endDate}
                onChange={(v) => handleChange('endDate', v)}
                placeholder="종료일"
              />
              {errors.endDate && (
                <p className="text-sm text-destructive">{errors.endDate}</p>
              )}
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="isRecurring"
              checked={formData.isRecurring}
              onCheckedChange={(checked) => handleChange('isRecurring', checked === true)}
            />
            <Label htmlFor="isRecurring" className="cursor-pointer">
              매년 반복
            </Label>
          </div>

          <FormField
            label="메모"
            type="textarea"
            value={formData.memo}
            onChange={(v) => handleChange('memo', v)}
            placeholder="메모"
            rows={3}
          />
        </div>

        <DialogFooter>
          {mode === 'edit' && (
            <Button
              variant="outline"
              onClick={handleDelete}
              disabled={isDeleting || isSaving}
              className="mr-auto text-destructive hover:bg-destructive hover:text-destructive-foreground"
            >
              {isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              삭제
            </Button>
          )}
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving || isDeleting}>
            취소
          </Button>
          <Button onClick={handleSubmit} disabled={isSaving || isDeleting}>
            {isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            {mode === 'create' ? '등록' : '수정'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
