import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { DateField } from '@/components/ui/date-field';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import type { TimelineEvent, TimelineEventType } from './ProjectTimeline';
import type { HistoryEntry } from './history-types';

interface EditEventDialogProps {
  event: TimelineEvent | null;
  onOpenChange: (open: boolean) => void;
  onRecordHistory?: (entry: HistoryEntry) => void;
}

export function EditEventDialog({ event, onOpenChange, onRecordHistory }: EditEventDialogProps) {
  const { t } = useTranslation();
  const [title, setTitle] = useState('');
  const [type, setType] = useState<TimelineEventType>('milestone');
  const [date, setDate] = useState<Date | undefined>();
  const [endDate, setEndDate] = useState<Date | undefined>();

  const pendingPrevRef = useRef<HistoryEntry | null>(null);

  const utils = trpc.useUtils();

  useEffect(() => {
    if (event) {
      setTitle(event.title);
      setType(event.type ?? 'milestone');
      setDate(new Date(event.date));
      if (event.type === 'activity' && event.endDate) {
        setEndDate(new Date(event.endDate));
      } else {
        setEndDate(undefined);
      }
    }
  }, [event]);

  const { notify, notifyError } = useNotify();
  const isActivity = type === 'activity';

  const updateEvent = trpc.timelineEvents.update.useMutation({
    onSuccess: () => {
      notify('success', 'toast.timeline.updated');
      void utils.timelineEvents.list.invalidate();
      if (pendingPrevRef.current) {
        onRecordHistory?.(pendingPrevRef.current);
        pendingPrevRef.current = null;
      }
      onOpenChange(false);
    },
    onError: (err) => {
      pendingPrevRef.current = null;
      notifyError('toast.timeline.updateError', err);
    },
  });

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!event || !title.trim() || !date) return;

    if (isActivity) {
      const hasEnd = endDate && endDate.getTime() !== date.getTime();
      const nextDate = date.getTime();
      const nextEndDate = hasEnd ? endDate!.getTime() : null;
      pendingPrevRef.current = {
        kind: 'update',
        id: event.id,
        prev: {
          title: event.title,
          type: (event.type ?? 'milestone') as 'milestone' | 'checkpoint' | 'activity',
          date: event.date,
          endDate: event.endDate ?? null,
        },
        next: { title: title.trim(), type: 'activity', date: nextDate, endDate: nextEndDate },
      };
      updateEvent.mutate({ id: event.id, title: title.trim(), type: 'activity', date: nextDate, endDate: nextEndDate });
    } else {
      const nextDate = date.getTime();
      pendingPrevRef.current = {
        kind: 'update',
        id: event.id,
        prev: {
          title: event.title,
          type: (event.type ?? 'milestone') as 'milestone' | 'checkpoint' | 'activity',
          date: event.date,
          endDate: event.endDate ?? null,
        },
        next: { title: title.trim(), type, date: nextDate, endDate: null },
      };
      updateEvent.mutate({ id: event.id, title: title.trim(), type, date: nextDate, endDate: null });
    }
  }

  const canSubmit = title.trim() && date;

  return (
    <Dialog open={!!event} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[420px]">
        <DialogHeader>
          <DialogTitle>{t('timeline.editEventTitle')}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          <ToggleGroup
            type="single"
            value={type}
            onValueChange={(v) => { if (v) setType(v as TimelineEventType); }}
            className="justify-start"
          >
            <ToggleGroupItem value="milestone" className="text-xs px-3">{t('timeline.typeMilestone')}</ToggleGroupItem>
            <ToggleGroupItem value="checkpoint" className="text-xs px-3">{t('timeline.typeCheckpoint')}</ToggleGroupItem>
            <ToggleGroupItem value="activity" className="text-xs px-3">{t('timeline.typeActivity')}</ToggleGroupItem>
          </ToggleGroup>

          <Input
            placeholder={t('timeline.eventTitlePlaceholder')}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            autoFocus
          />

          {isActivity ? (
            <div className="flex gap-2">
              <DateField
                value={date}
                onChange={setDate}
                placeholder={t('timeline.pickStart')}
                aria-label={t('timeline.pickStart')}
                className="flex-1"
              />
              <DateField
                value={endDate}
                onChange={setEndDate}
                minDate={date}
                placeholder={t('timeline.pickEnd')}
                aria-label={t('timeline.pickEnd')}
                className="flex-1"
              />
            </div>
          ) : (
            <DateField
              value={date}
              onChange={setDate}
              placeholder={t('timeline.pickDate')}
              aria-label={t('timeline.pickDate')}
            />
          )}

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              {t('common.cancel')}
            </Button>
            <Button type="submit" disabled={!canSubmit || updateEvent.isPending}>
              {t('common.save')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
