import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useFormatPrefs, formatDate } from '@/lib/date';
import { CalendarIcon, Check } from 'lucide-react';
import { type DateRange } from 'react-day-picker';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import type { TimelineEventType } from './ProjectTimeline';
import type { HistoryEntry } from './history-types';

interface AddEventDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultProjectId?: string;
  onRecordHistory?: (entry: HistoryEntry) => void;
}

interface AddedEntry {
  title: string;
  date: Date;
  endDate?: Date;
  type: TimelineEventType;
}

export function AddEventDialog({ open, onOpenChange, defaultProjectId, onRecordHistory }: AddEventDialogProps) {
  const { t } = useTranslation();
  const prefs = useFormatPrefs();
  const [title, setTitle] = useState('');
  const [type, setType] = useState<TimelineEventType>('milestone');
  const [dateRange, setDateRange] = useState<DateRange | undefined>();
  const [singleDate, setSingleDate] = useState<Date | undefined>();
  const [projectId, setProjectId] = useState(defaultProjectId ?? '');
  const [added, setAdded] = useState<AddedEntry[]>([]);

  const showProjectSelect = !defaultProjectId;
  const isActivity = type === 'activity';

  const { data: projectsList } = trpc.projects.listAll.useQuery(undefined, {
    enabled: showProjectSelect,
  });
  const utils = trpc.useUtils();
  const { notify, notifyError } = useNotify();

  const createEvent = trpc.timelineEvents.create.useMutation({
    onSuccess: (data, variables) => {
      notify('success', 'toast.timeline.created');
      void utils.timelineEvents.list.invalidate();
      onRecordHistory?.({
        kind: 'create',
        id: data.id,
        payload: {
          id: data.id,
          projectId: variables.projectId ?? null,
          title: variables.title,
          date: variables.date,
          endDate: variables.endDate ?? null,
          type: (variables.type ?? 'milestone') as 'milestone' | 'checkpoint' | 'activity',
          isCompleted: 0,
          isAiSuggested: 0,
        },
      });
      setAdded((prev) => [
        ...prev,
        {
          title: variables.title,
          date: new Date(variables.date),
          endDate: variables.endDate ? new Date(variables.endDate) : undefined,
          type: variables.type as TimelineEventType,
        },
      ]);
      setTitle('');
      setDateRange(undefined);
      setSingleDate(undefined);
    },
    onError: (err) => notifyError('toast.timeline.createError', err),
  });

  function handleClose() {
    setTitle('');
    setType('milestone');
    setDateRange(undefined);
    setSingleDate(undefined);
    setProjectId(defaultProjectId ?? '');
    setAdded([]);
    onOpenChange(false);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const pid = defaultProjectId || projectId || undefined;

    if (isActivity) {
      if (!title.trim() || !dateRange?.from) return;
      const hasDuration = dateRange.to && dateRange.to.getTime() !== dateRange.from.getTime();
      createEvent.mutate({
        title: title.trim(),
        date: dateRange.from.getTime(),
        endDate: hasDuration ? dateRange.to!.getTime() : undefined,
        type: 'activity',
        projectId: pid,
      });
    } else {
      if (!title.trim() || !singleDate) return;
      createEvent.mutate({
        title: title.trim(),
        date: singleDate.getTime(),
        type,
        projectId: pid,
      });
    }
  }

  const canSubmit = isActivity ? (title.trim() && dateRange?.from) : (title.trim() && singleDate);

  return (
    <Dialog open={open} onOpenChange={(v) => { if (!v) handleClose(); else onOpenChange(v); }}>
      <DialogContent className="sm:max-w-[420px]">
        <DialogHeader>
          <DialogTitle>{t('timeline.addEventTitle')}</DialogTitle>
        </DialogHeader>

        {added.length > 0 && (
          <ScrollArea className="max-h-32">
            <div className="flex flex-col gap-1.5">
              {added.map((entry, i) => (
                <div key={i} className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Check className="h-3.5 w-3.5 text-chart-2 shrink-0" />
                  <span className="truncate">{entry.title}</span>
                  <span className="ml-auto text-xs shrink-0">
                    {entry.type === 'milestone' ? t('timeline.typeMilestone') : entry.type === 'checkpoint' ? t('timeline.typeCheckpoint') : t('timeline.typeActivity')}
                  </span>
                </div>
              ))}
            </div>
          </ScrollArea>
        )}

        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          {/* Event type selector */}
          <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
          />

          {/* Date picker: range for activities, single for milestone/checkpoint */}
          {isActivity ? (
            <Popover>
              <PopoverTrigger asChild>
                <Button type="button" variant="outline" className="justify-start px-2.5 font-normal">
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {dateRange?.from ? (
                    dateRange.to && dateRange.to.getTime() !== dateRange.from.getTime() ? (
                      <>{formatDate(dateRange.from.getTime(), prefs)} – {formatDate(dateRange.to.getTime(), prefs)}</>
                    ) : (
                      formatDate(dateRange.from.getTime(), prefs)
                    )
                  ) : (
                    <span className="text-muted-foreground">{t('timeline.pickDateRange')}</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="range"
                  defaultMonth={dateRange?.from}
                  selected={dateRange}
                  onSelect={setDateRange}
                  numberOfMonths={2}
                />
              </PopoverContent>
            </Popover>
          ) : (
            <Popover>
              <PopoverTrigger asChild>
                <Button type="button" variant="outline" className="justify-start px-2.5 font-normal">
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {singleDate ? (
                    formatDate(singleDate.getTime(), prefs)
                  ) : (
                    <span className="text-muted-foreground">{t('timeline.pickDate')}</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="single"
                  selected={singleDate}
                  onSelect={setSingleDate}
                />
              </PopoverContent>
            </Popover>
          )}

          {showProjectSelect && (
            <Select value={projectId} onValueChange={setProjectId}>
              <SelectTrigger>
                <SelectValue placeholder={t('timeline.selectProjectOptional')} />
              </SelectTrigger>
              <SelectContent>
                {projectsList?.map((p) => (
                  <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}

          <DialogFooter>
            <Button type="button" variant="outline" onClick={handleClose}>
              {added.length > 0 ? t('common.done') : t('common.cancel')}
            </Button>
            <Button type="submit" disabled={!canSubmit || createEvent.isPending}>
              {added.length > 0 ? t('timeline.addAnother') : t('common.add')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
