import { createFileRoute } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { Lock, Plus, Volume2, X, Camera, Sparkles, Trash2, Box } from "lucide-react";
import { ActionButton, Card, Pill, PageTitle, Screen } from "@/components/ui-kit";
import { svgs } from "@/assets/svgMap";

export const Route = createFileRoute("/memory")({
  head: () => ({
    meta: [
      { title: "Memory Album · NeuroSaathi" },
      {
        name: "description",
        content:
          "Private family album with real photo uploads, audio stories, and reminiscence prompts.",
      },
      { property: "og:title", content: "Memory Album · NeuroSaathi" },
      {
        property: "og:description",
        content: "Private family album with photo uploads and audio stories.",
      },
    ],
  }),
  component: MemoryAlbum,
});

const categories = ["All", "Family", "Travel", "Festivals", "Nature", "General"];

interface MemoryPhoto {
  id: number;
  title: string;
  category: string;
  url: string;
  desc: string;
  date: string;
}

const defaultPhotos: MemoryPhoto[] = [
  {
    id: 1,
    title: "Diwali 2019",
    category: "Festivals",
    url: "https://images.unsplash.com/photo-1514252441315-9c869e578c7f?w=600&auto=format&fit=crop&q=80",
    desc: "Sabhi parivar ke log ek saath diye jala rahe the.",
    date: "2019-10-27",
  },
  {
    id: 2,
    title: "Goa trip",
    category: "Travel",
    url: "https://images.unsplash.com/photo-1512343879784-a960bf40e7f2?w=600&auto=format&fit=crop&q=80",
    desc: "Samudra ke kinare shaam ka sundar nazara.",
    date: "2021-02-14",
  },
  {
    id: 3,
    title: "Nani ka ghar",
    category: "Family",
    url: "https://images.unsplash.com/photo-1581579438747-1dc8d17ccce4?w=600&auto=format&fit=crop&q=80",
    desc: "Bachpan ki yaadien aur dadi ke haath ka khana.",
    date: "2018-06-10",
  },
  {
    id: 4,
    title: "Garden morning",
    category: "Nature",
    url: "https://images.unsplash.com/photo-1585320806297-9794b3e4eeae?w=600&auto=format&fit=crop&q=80",
    desc: "Subah ki taazi hawa mein phoolon ki dekhbhaal.",
    date: "2023-04-05",
  },
];

function MemoryAlbum() {
  const [cat, setCat] = useState("All");
  const [photos, setPhotos] = useState<MemoryPhoto[]>(defaultPhotos);
  const [openId, setOpenId] = useState<number | null>(null);
  const [uploading, setUploading] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newCat, setNewCat] = useState("Family");
  const [newDesc, setNewDesc] = useState("");
  const [newUrl, setNewUrl] = useState("");

  useEffect(() => {
    const saved = localStorage.getItem("neurosaathi_memories");
    if (saved) {
      try {
        setPhotos(JSON.parse(saved));
      } catch (e) {
        console.error("Failed to parse saved memories", e);
      }
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("neurosaathi_memories", JSON.stringify(photos));
  }, [photos]);

  const shown = cat === "All" ? photos : photos.filter((p) => p.category === cat);
  const open = photos.find((p) => p.id === openId);

  const handleAddPhoto = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTitle) return;
    const item: MemoryPhoto = {
      id: Date.now(),
      title: newTitle,
      category: newCat,
      url:
        newUrl ||
        "https://images.unsplash.com/photo-1516627145497-ae6968895b74?w=600&auto=format&fit=crop&q=80",
      desc: newDesc || "Yaadgaar pal.",
      date: new Date().toISOString().split("T")[0],
    };
    setPhotos([item, ...photos]);
    setNewTitle("");
    setNewDesc("");
    setNewUrl("");
    setUploading(false);
  };

  const deletePhoto = (id: number) => {
    setPhotos(photos.filter((p) => p.id !== id));
    setOpenId(null);
  };

  const speakStory = (text: string) => {
    if ("speechSynthesis" in window) {
      window.speechSynthesis.cancel();
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = "hi-IN";
      window.speechSynthesis.speak(utterance);
    }
  };

  return (
    <Screen>
      <PageTitle title="Memory Album" subtitle="Aapki yaadein, private aur safe" />

      <div className="overflow-hidden rounded-3xl border border-border shadow-sm mb-6 relative group bg-secondary/30">
        <img
          src={svgs.memoryAlbumHero}
          alt="Memory Album"
          className="h-32 w-full object-cover transition-transform duration-500 group-hover:scale-105 opacity-90"
          referrerPolicy="no-referrer"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent flex items-end p-4">
          <div className="text-white">
            <p className="font-display text-base font-bold">Nostalgia & Connection</p>
          </div>
        </div>
      </div>

      <div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4 mb-2">
        {categories.map((c) => (
          <button
            key={c}
            onClick={() => setCat(c)}
            className={`press min-h-[40px] shrink-0 rounded-full px-4 text-sm font-semibold ${
              cat === c
                ? "gradient-primary text-primary-foreground"
                : "border border-border bg-card text-muted-foreground"
            }`}
          >
            {c}
          </button>
        ))}
      </div>

      {shown.length === 0 ? (
        <Card className="flex flex-col items-center justify-center p-8 text-center text-muted-foreground border-dashed">
          <img
            src={svgs.emptyState}
            alt="Empty"
            className="mb-3 h-20 w-20 opacity-80"
            referrerPolicy="no-referrer"
          />
          <p className="text-sm">Koi memory nahi mili. Nayi photo add karein.</p>
        </Card>
      ) : (
        <div className="grid grid-cols-2 gap-3">
          {shown.map((p) => (
            <button
              key={p.id}
              onClick={() => setOpenId(p.id)}
              className="press glass-card overflow-hidden p-0 text-left"
            >
              <div className="aspect-[4/3] bg-muted relative">
                <img
                  src={p.url}
                  alt={p.title}
                  className="absolute inset-0 h-full w-full object-cover"
                />
              </div>
              <div className="space-y-1 p-3">
                <p className="truncate text-sm font-semibold">{p.title}</p>
                <p className="text-[11px] text-muted-foreground">
                  {p.category} · {p.date}
                </p>
              </div>
            </button>
          ))}
        </div>
      )}

      <ActionButton icon={Plus} className="w-full mt-4" onClick={() => setUploading(true)}>
        Upload memory
      </ActionButton>

      <Card className="bg-secondary/60">
        <div className="flex items-center gap-3">
          <div className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-primary/12 text-primary">
            <Lock className="h-[18px] w-[18px]" />
          </div>
          <p className="min-w-0 flex-1 text-xs text-muted-foreground">
            Private by default. Photos aapki permission ke bina kahin share nahi hote.
          </p>
        </div>
      </Card>

      {uploading ? (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <button
            onClick={() => setUploading(false)}
            className="absolute inset-0 bg-foreground/50"
          />
          <Card className="relative z-10 w-full max-w-md space-y-4 bg-card p-6">
            <h2 className="font-display text-lg font-semibold">Nayi Memory Jodein</h2>
            <form onSubmit={handleAddPhoto} className="space-y-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground">Title</label>
                <input
                  type="text"
                  required
                  value={newTitle}
                  onChange={(e) => setNewTitle(e.target.value)}
                  placeholder="Jaise: Diwali Celebration"
                  className="mt-1 w-full rounded-xl border border-border bg-background px-3 py-2 text-sm"
                />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">Category</label>
                <select
                  value={newCat}
                  onChange={(e) => setNewCat(e.target.value)}
                  className="mt-1 w-full rounded-xl border border-border bg-background px-3 py-2 text-sm"
                >
                  {categories
                    .filter((c) => c !== "All")
                    .map((c) => (
                      <option key={c} value={c}>
                        {c}
                      </option>
                    ))}
                </select>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">
                  Image URL (Unsplash or direct link)
                </label>
                <input
                  type="url"
                  value={newUrl}
                  onChange={(e) => setNewUrl(e.target.value)}
                  placeholder="https://images.unsplash.com/..."
                  className="mt-1 w-full rounded-xl border border-border bg-background px-3 py-2 text-sm"
                />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">
                  Story / Description
                </label>
                <textarea
                  value={newDesc}
                  onChange={(e) => setNewDesc(e.target.value)}
                  placeholder="Is pal ke baare mein kuch likhein..."
                  className="mt-1 w-full rounded-xl border border-border bg-background px-3 py-2 text-sm"
                />
              </div>
              <div className="flex gap-2 pt-2">
                <ActionButton type="submit" className="flex-1">
                  Save
                </ActionButton>
                <ActionButton
                  type="button"
                  variant="outline"
                  onClick={() => setUploading(false)}
                  className="flex-1"
                >
                  Cancel
                </ActionButton>
              </div>
            </form>
          </Card>
        </div>
      ) : null}

      {open ? (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center sm:justify-center">
          <button
            aria-label="Close photo"
            onClick={() => setOpenId(null)}
            className="absolute inset-0 animate-in fade-in bg-foreground/50 duration-200"
          />
          <div className="glass-panel animate-in slide-in-from-bottom relative mx-auto w-full max-w-md rounded-t-4xl sm:rounded-3xl border p-5 pb-[max(1.5rem,env(safe-area-inset-bottom))] duration-300">
            <div className="flex items-start justify-between gap-3 mb-3">
              <div>
                <h2 className="truncate font-display text-lg font-semibold">{open.title}</h2>
                <Pill tone="primary" className="mt-1">
                  {open.category} · {open.date}
                </Pill>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => speakStory(open.desc)}
                  aria-label="Play audio story"
                  className="press grid h-9 w-9 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
                >
                  <Volume2 className="h-4 w-4" />
                </button>
                <button
                  onClick={() => deletePhoto(open.id)}
                  aria-label="Delete photo"
                  className="press grid h-9 w-9 shrink-0 place-items-center rounded-full bg-destructive/15 text-destructive"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
                <button
                  onClick={() => setOpenId(null)}
                  aria-label="Close"
                  className="press grid h-9 w-9 shrink-0 place-items-center rounded-full border border-border bg-card"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            </div>

            <div className="aspect-[4/3] rounded-2xl overflow-hidden mb-3 bg-muted relative">
              <img
                src={open.url}
                alt={open.title}
                className="absolute inset-0 h-full w-full object-cover"
              />
            </div>

            <p className="text-sm text-foreground/85">{open.desc}</p>
            <div className="mt-4 rounded-2xl bg-secondary/60 p-3 text-xs text-muted-foreground">
              💡 <strong>Reminiscence Prompt:</strong> Aapko is pal mein kaun-kaun yaad aa raha hai?
              Yeh kahan ki tasveer hai?
            </div>
          </div>
        </div>
      ) : null}
    </Screen>
  );
}
