import { createFileRoute } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import {
  AlarmClock,
  Check,
  Droplets,
  Footprints,
  Phone,
  Pill as PillIcon,
  Plus,
  Stethoscope,
  Trash2,
  Clock,
} from "lucide-react";
import { ActionButton, Card, PageTitle, Pill, Screen } from "@/components/ui-kit";
import { svgs } from "@/assets/svgMap";

export const Route = createFileRoute("/reminders")({
  head: () => ({
    meta: [
      { title: "Reminders & Tasks · NeuroSaathi" },
      {
        name: "description",
        content:
          "Manage daily medication, water, walking, and appointment reminders with snooze, add and delete capabilities.",
      },
      { property: "og:title", content: "Reminders & Tasks · NeuroSaathi" },
      {
        property: "og:description",
        content: "Daily medication and routine reminders with add/snooze/delete.",
      },
    ],
  }),
  component: Reminders,
});

interface ReminderItem {
  id: number;
  title: string;
  desc: string;
  time: string;
  type: string;
  done: boolean;
}

const defaultReminders: ReminderItem[] = [
  {
    id: 1,
    title: "Morning medicine",
    desc: "1 tablet after breakfast",
    time: "8:00 AM",
    type: "Medication",
    done: true,
  },
  { id: 2, title: "Drink water", desc: "2 glasses", time: "11:30 AM", type: "Water", done: false },
  {
    id: 3,
    title: "Evening walk",
    desc: "20 minutes, slow pace",
    time: "5:30 PM",
    type: "Walking",
    done: false,
  },
  {
    id: 4,
    title: "Call with Priya",
    desc: "Weekly family call",
    time: "6:00 PM",
    type: "Family",
    done: false,
  },
  {
    id: 5,
    title: "Doctor appointment",
    desc: "Dr. Mehta · City Clinic",
    time: "Tomorrow 11:00 AM",
    type: "Appointment",
    done: false,
  },
];

function Reminders() {
  const [items, setItems] = useState<ReminderItem[]>(defaultReminders);
  const [tab, setTab] = useState<"today" | "done">("today");
  const [adding, setAdding] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newDesc, setNewDesc] = useState("");
  const [newTime, setNewTime] = useState("09:00 AM");
  const [newType, setNewType] = useState("Medication");

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

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

  const toggle = (id: number) =>
    setItems((prev) => prev.map((i) => (i.id === id ? { ...i, done: !i.done } : i)));

  const deleteItem = (id: number) => setItems((prev) => prev.filter((i) => i.id !== id));

  const snooze = (id: number) => {
    setItems((prev) => prev.map((i) => (i.id === id ? { ...i, time: i.time + " (Snoozed)" } : i)));
  };

  const handleAdd = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTitle) return;
    const newItem: ReminderItem = {
      id: Date.now(),
      title: newTitle,
      desc: newDesc || "Dhyan rahe",
      time: newTime,
      type: newType,
      done: false,
    };
    setItems([newItem, ...items]);
    setNewTitle("");
    setNewDesc("");
    setAdding(false);
  };

  const shown = items.filter((i) => (tab === "today" ? !i.done : i.done));

  return (
    <Screen>
      <PageTitle title="Reminders" subtitle="Aapke roz ke zaroori kaam aur dawaaiyaan" />

      <div className="overflow-hidden rounded-3xl border border-border shadow-sm mb-6 relative group bg-secondary/30">
        <img
          src={svgs.remindersHero}
          alt="Reminders"
          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">Daily Routine</p>
          </div>
        </div>
      </div>

      <div className="glass-card flex gap-1.5 p-1.5 mb-4">
        {(["today", "done"] as const).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`press min-h-[44px] flex-1 rounded-xl text-sm font-semibold capitalize ${
              tab === t ? "gradient-primary text-primary-foreground" : "text-muted-foreground"
            }`}
          >
            {t === "today"
              ? `Pending (${items.filter((i) => !i.done).length})`
              : `Completed (${items.filter((i) => i.done).length})`}
          </button>
        ))}
      </div>

      <ActionButton icon={Plus} onClick={() => setAdding(true)} className="w-full mb-4">
        Add reminder
      </ActionButton>

      {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"
          />
          <h3 className="font-display font-semibold text-foreground mb-1">
            {tab === "today" ? "Sab kaam ho gaye!" : "Abhi kuch complete nahi hua"}
          </h3>
          <p className="text-sm">
            {tab === "today"
              ? "Aaj ke saare reminders complete hain. Shabaash!"
              : "Jaise hi aap koi reminder complete karenge, wo yahan dikhega."}
          </p>
        </Card>
      ) : (
        <div className="space-y-3">
          {shown.map((r) => (
            <Card key={r.id}>
              <div className="flex items-start gap-3">
                <div
                  className={`grid h-11 w-11 shrink-0 place-items-center rounded-2xl ${
                    r.done ? "bg-success/15 text-success" : "bg-primary/12 text-primary"
                  }`}
                >
                  {r.type === "Water" ? (
                    <Droplets className="h-5 w-5" />
                  ) : r.type === "Walking" ? (
                    <Footprints className="h-5 w-5" />
                  ) : r.type === "Phone" ? (
                    <Phone className="h-5 w-5" />
                  ) : r.type === "Appointment" ? (
                    <Stethoscope className="h-5 w-5" />
                  ) : (
                    <PillIcon className="h-5 w-5" />
                  )}
                </div>
                <div className="min-w-0 flex-1">
                  <p
                    className={`text-[15px] font-semibold ${r.done ? "line-through text-muted-foreground" : ""}`}
                  >
                    {r.title}
                  </p>
                  <p className="mt-0.5 text-sm text-muted-foreground">{r.desc}</p>
                  <div className="mt-2 flex flex-wrap gap-2 items-center">
                    <Pill tone={r.done ? "success" : "warning"}>
                      <AlarmClock className="h-3 w-3" /> {r.time}
                    </Pill>
                    {!r.done && (
                      <button
                        onClick={() => snooze(r.id)}
                        className="text-[11px] font-semibold text-primary inline-flex items-center gap-1"
                      >
                        <Clock className="h-3 w-3" /> Snooze 15m
                      </button>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-1.5">
                  <button
                    onClick={() => toggle(r.id)}
                    aria-label={r.done ? "Mark as pending" : "Mark as done"}
                    className={`press grid h-11 w-11 shrink-0 place-items-center rounded-full border ${
                      r.done
                        ? "border-success/40 bg-success/15 text-success"
                        : "border-border bg-card text-muted-foreground hover:border-primary hover:text-primary"
                    }`}
                  >
                    <Check className="h-5 w-5" />
                  </button>
                  <button
                    onClick={() => deleteItem(r.id)}
                    aria-label="Delete reminder"
                    className="press grid h-9 w-9 shrink-0 place-items-center rounded-full text-destructive hover:bg-destructive/10"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {adding ? (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <button onClick={() => setAdding(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">Naya Reminder Jodein</h2>
            <form onSubmit={handleAdd} 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: Dopahar ki dawa"
                  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">Type</label>
                <select
                  value={newType}
                  onChange={(e) => setNewType(e.target.value)}
                  className="mt-1 w-full rounded-xl border border-border bg-background px-3 py-2 text-sm"
                >
                  <option value="Medication">Medication</option>
                  <option value="Water">Water</option>
                  <option value="Walking">Walking</option>
                  <option value="Appointment">Appointment</option>
                  <option value="Family">Family Call</option>
                </select>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">Time</label>
                <input
                  type="text"
                  required
                  value={newTime}
                  onChange={(e) => setNewTime(e.target.value)}
                  placeholder="2:00 PM"
                  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">Description</label>
                <textarea
                  value={newDesc}
                  onChange={(e) => setNewDesc(e.target.value)}
                  placeholder="Jaise: 1 tablet khane ke baad"
                  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={() => setAdding(false)}
                  className="flex-1"
                >
                  Cancel
                </ActionButton>
              </div>
            </form>
          </Card>
        </div>
      ) : null}
    </Screen>
  );
}
