"use client";

import { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import type { EventHint } from "@/lib/mail/extract-event-hints";

/**
 * MA3 — inline "📅 Add to calendar" CTA rendered next to a Gmail thread row
 * when {@link extractEventHints} surfaces ≥1 hint. Stores accepted events in
 * `localStorage` under `sag.calendar.suggested_events`; the calendar
 * aggregator reads that key and emits them on the calendar grid.
 *
 * Stays fully client-side — never hits the network. Form is inline (not a
 * modal) so it appears as a row addendum below the thread.
 */

export type SuggestedEvent = {
  id: string;
  source: "gmail";
  threadId: string;
  threadSubject?: string;
  title: string;
  /** YYYY-MM-DD. */
  date: string;
  /** HH:mm (24h) — optional, hint may be date-only. */
  time?: string;
  /** Duration in minutes. Default 60. */
  duration: number;
  notes?: string;
  status: "suggested" | "accepted" | "dismissed";
  createdAt: string;
  updatedAt: string;
};

export const SUGGESTED_EVENTS_KEY = "sag.calendar.suggested_events";

interface Props {
  hint: EventHint;
  threadId: string;
  threadSubject?: string;
}

/**
 * Stable-ish id so re-clicks on the same hint don't pile up duplicates.
 * Combines threadId + the hint's raw matched text. Deduping in the writer
 * keeps the localStorage list bounded even across multiple inbox refreshes.
 */
function makeSuggestedId(threadId: string, rawText: string): string {
  const slug = rawText
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 40);
  return `gmail:${threadId}:${slug || "hint"}`;
}

export function CreateCalendarEntryButton({ hint, threadId, threadSubject }: Props) {
  const [events, setEvents] = useLocalStorage<SuggestedEvent[]>(SUGGESTED_EVENTS_KEY, []);
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState(threadSubject ?? "");
  const [date, setDate] = useState(hint.date ?? "");
  const [time, setTime] = useState(hint.time ?? "");
  const [duration, setDuration] = useState<number>(hint.duration ?? 60);
  const [notes, setNotes] = useState("");

  const eventId = makeSuggestedId(threadId, hint.rawText);
  const alreadySaved = events.some(
    (e) => e.id === eventId && e.status !== "dismissed"
  );

  function handleOpen(e: React.MouseEvent) {
    // The row is clickable (it opens the thread) — don't bubble the form open.
    e.stopPropagation();
    setOpen((v) => !v);
  }

  function handleSave(e: React.MouseEvent) {
    e.stopPropagation();
    if (!date || !title.trim()) return;
    const now = new Date().toISOString();
    const event: SuggestedEvent = {
      id: eventId,
      source: "gmail",
      threadId,
      threadSubject,
      title: title.trim(),
      date,
      time: time || undefined,
      duration: Number.isFinite(duration) && duration > 0 ? duration : 60,
      notes: notes.trim() || undefined,
      status: "suggested",
      createdAt: now,
      updatedAt: now,
    };
    setEvents((prev) => {
      const idx = prev.findIndex((e) => e.id === event.id);
      if (idx >= 0) {
        const next = prev.slice();
        next[idx] = { ...event, createdAt: prev[idx].createdAt };
        return next;
      }
      return [...prev, event];
    });
    setOpen(false);
  }

  function handleCancel(e: React.MouseEvent) {
    e.stopPropagation();
    setOpen(false);
  }

  if (alreadySaved && !open) {
    return (
      <Link
        href="/app/calendar"
        onClick={(e) => e.stopPropagation()}
        className="inline-flex items-center gap-1 rounded-full border border-rose-500/30 bg-rose-500/10 px-2 py-0.5 text-[10px] text-rose-600 hover:bg-rose-500/20 transition-colors"
        title="Saved as a calendar suggestion"
      >
        <span aria-hidden>📅</span>
        <span>Saved &rarr; /app/calendar</span>
      </Link>
    );
  }

  return (
    <>
      <button
        type="button"
        onClick={handleOpen}
        className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] transition-colors ${
          open
            ? "border-rose-500 bg-rose-500/10 text-rose-700"
            : "border-rose-500/30 bg-rose-500/5 text-rose-600 hover:bg-rose-500/15"
        }`}
        title={`Detected: ${hint.rawText} (${hint.confidence} confidence)`}
      >
        <span aria-hidden>📅</span>
        <span>Add to calendar</span>
      </button>
      {open && (
        <div
          onClick={(e) => e.stopPropagation()}
          className="mt-2 w-full rounded-md border border-rose-500/30 bg-rose-500/5 p-3 space-y-2"
        >
          <div className="text-[10px] uppercase tracking-wider text-rose-700/80">
            New calendar entry from this email
          </div>
          <div className="grid gap-2 sm:grid-cols-2">
            <label className="block text-[11px] sm:col-span-2">
              <span className="text-muted-foreground">Title</span>
              <Input
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Event title"
                className="mt-0.5 h-8 text-sm"
              />
            </label>
            <label className="block text-[11px]">
              <span className="text-muted-foreground">Date</span>
              <Input
                type="date"
                value={date}
                onChange={(e) => setDate(e.target.value)}
                className="mt-0.5 h-8 text-sm"
              />
            </label>
            <label className="block text-[11px]">
              <span className="text-muted-foreground">Time (optional)</span>
              <Input
                type="time"
                value={time}
                onChange={(e) => setTime(e.target.value)}
                className="mt-0.5 h-8 text-sm"
              />
            </label>
            <label className="block text-[11px]">
              <span className="text-muted-foreground">Duration (min)</span>
              <Input
                type="number"
                min={5}
                max={1440}
                step={5}
                value={duration}
                onChange={(e) => setDuration(parseInt(e.target.value, 10) || 60)}
                className="mt-0.5 h-8 text-sm"
              />
            </label>
          </div>
          <label className="block text-[11px]">
            <span className="text-muted-foreground">Notes</span>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="Optional notes…"
              className="mt-0.5 w-full min-h-[48px] rounded-md border border-input bg-background px-2 py-1 text-sm"
            />
          </label>
          <div className="flex items-center justify-end gap-2 pt-1">
            <Button variant="ghost" size="sm" onClick={handleCancel}>
              Cancel
            </Button>
            <Button
              variant="brand"
              size="sm"
              onClick={handleSave}
              disabled={!date || !title.trim()}
            >
              Save to calendar
            </Button>
          </div>
          <p className="text-[10px] text-muted-foreground">
            Detected from this email: <span className="font-mono">{hint.rawText}</span>{" "}
            ({hint.confidence} confidence). Saved locally — surfaces on{" "}
            <Link href="/app/calendar" className="underline">
              /app/calendar
            </Link>
            .
          </p>
        </div>
      )}
    </>
  );
}
