import { useState, useMemo } from "react";
import {
 CalendarDays,
 CheckCircle2,
 Clock,
 User,
 LayoutGrid,
 GanttChartSquare,
 Calendar as CalendarIcon,
 History,
 FlaskConical,
} from "lucide-react";
import { format, isAfter, isBefore, startOfDay, eachDayOfInterval, parseISO } from "date-fns";
import { Timeline } from "../components/Timeline";
import { Scheduler } from "../components/Scheduler";
import { EventPopoverContent } from "../components/EventPopoverContent";
import type { DisplayedTimelineEvent } from "../components/Timeline";
import { FullScreenCalendar } from "../components/FullScreenCalendar";
import { useHealthStore } from "../store/useHealthStore";
import { cn } from "../utils/helpers";
import { formatSpecificTime } from "../utils/eventTime";
import { Popover, PopoverContent, PopoverTrigger } from "../components/ui/popover";
import type { Appointment, LabResult, Medication, TimelineEvent, ImagingEvent } from "../types/medical";
import { useLocation } from "react-router-dom";

type ViewMode = "timeline" | "scheduler" | "calendar" | "schedule";

export function TimelinePage() {
 const today = startOfDay(new Date());
 const [viewMode, setViewMode] = useState<ViewMode>("timeline");
 const [selectedCalendarEvent, setSelectedCalendarEvent] = useState<TimelineEvent | null>(null);
 const location = useLocation();
 const focusDate = (location.state as { focusDate?: string } | null)?.focusDate;

 const { appointments, labResults, medications, vitals, vaccinations, imaging, injectTestEvents, clearTestEvents } = useHealthStore();

 // Filter events for the Schedule & History tab panels
 const upcomingAppointments = appointments
  .filter((e) => isAfter(new Date(e.date), today))
  .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

 const pastAppointmentsAndTests = [...appointments, ...labResults, ...(vaccinations || []), ...(imaging || [])]
  .filter(
   (e) =>
    isBefore(new Date(e.date), today) ||
    e.date === format(today, "yyyy-MM-dd")
  )
  .sort(
   (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
  );

 // Transform health store data into CalendarData format
 const calendarData = useMemo(() => {
  const dayMap = new Map<string, TimelineEvent[]>();

  const addToDay = (dateKey: string, event: TimelineEvent) => {
   if (!dayMap.has(dateKey)) dayMap.set(dateKey, []);
   dayMap.get(dateKey)!.push(event);
  };

  // Non-medication events: use their single date
  [...appointments, ...labResults, ...vitals, ...(vaccinations || []), ...(imaging || [])].forEach((event) => {
   addToDay(event.date, event);
  });

  // Medications: spread across each active day from startDate to endDate
  medications.forEach((event) => {
   const med = event as Medication;
   const start = parseISO(med.startDate || med.date);
   const end = parseISO(med.endDate || med.date);
   const effectiveEnd = end < start ? start : end;
   eachDayOfInterval({ start, end: effectiveEnd }).forEach((day) => {
    addToDay(format(day, "yyyy-MM-dd"), event);
   });
  });

  return Array.from(dayMap.entries()).map(([dateStr, events]) => ({
   day: new Date(dateStr),
   events,
  }));
 }, [appointments, labResults, medications, vitals, vaccinations, imaging]);

 const handleCalendarEventClick = (event: TimelineEvent) => {
  setSelectedCalendarEvent(event);
 };

 const TABS: Array<{ id: ViewMode; label: string; Icon: typeof LayoutGrid }> = [
  { id: "timeline", label: "Timeline", Icon: GanttChartSquare },
  { id: "scheduler", label: "Agenda", Icon: LayoutGrid },
  { id: "calendar", label: "Calendar", Icon: CalendarIcon },
  { id: "schedule", label: "Schedule & History", Icon: History },
 ];

 return (
  // Fill the patient shell's content area exactly: the wrapping div in App.tsx
  // adds p-8 (4rem total vertical), so 100vh - 4rem gives us the available
  // height with no page scroll. The page itself is a flex column so the tab
  // content stretches to fill the remaining space below the header.
  <div className="h-[calc(100vh-4rem)] flex flex-col">
   {/* Header — compact on desktop, stacked on smaller widths so the 4-tab switcher doesn't clip. */}
   <header className="mb-3 shrink-0 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
    <div className="min-w-0">
     <h1 className="text-[22px] font-semibold tracking-tight text-gray-900">
      Medical Timeline
     </h1>
     <p className="text-sm text-gray-500">
      Appointments, tests, and current prescriptions.
     </p>
    </div>

    <div className="flex min-w-0 items-center gap-2">
     {/* Dev: Test Data Injector — DEV builds only, tucked into a popover so it
         doesn't dominate the header. Frontend-only, never persisted. */}
      <Popover>
       <PopoverTrigger asChild>
        <button
         className="btn-icon"
         title="Inject test events (dev only)"
        >
         <FlaskConical size={16} />
        </button>
       </PopoverTrigger>
       <PopoverContent align="end" className="w-56">
        <p className="text-[10px] font-medium uppercase tracking-wider text-gray-400">
         Inject test events
        </p>
        <div className="mt-2 grid grid-cols-2 gap-1.5">
         {[50, 200, 500, 1000].map((n) => (
          <button
           key={n}
           onClick={() => injectTestEvents(n)}
           className="rounded-md border border-gray-100 bg-gray-50 px-2 py-1.5 text-xs font-medium text-gray-700 transition-colors hover:border-gray-200 hover:bg-white"
          >
           +{n}
          </button>
         ))}
        </div>
        <button
         onClick={clearTestEvents}
         className="mt-2 w-full rounded-md px-2 py-1.5 text-xs font-medium text-gray-500 transition-colors hover:bg-red-50 hover:text-red-600"
        >
         Clear injected
        </button>
       </PopoverContent>
      </Popover>

     {/* View Mode Switcher (4 tabs) */}
     <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto rounded-lg border border-gray-200 bg-gray-100 p-1 md:flex-none">
      {TABS.map(({ id, label, Icon }) => (
       <button
        key={id}
        onClick={() => setViewMode(id)}
        className={cn(
         "shrink-0 flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-all",
         viewMode === id
          ? "bg-white text-gray-900 shadow-sm"
          : "text-gray-500 hover:text-gray-800"
        )}
       >
        <Icon size={15} />
        <span className="whitespace-nowrap">{label}</span>
       </button>
      ))}
     </div>
    </div>
   </header>

   {/* Tab content — all four tabs stay mounted via display:none so each view
       preserves its own viewport state (Timeline pan/zoom, Scheduler week,
       Calendar month) when switching tabs. Each tab fills the remaining
       flex space. */}
   <section className="flex-1 min-h-0 flex flex-col">
    {/* Timeline tab — horizontal scroller w/ zoom presets, full-bleed */}
    <div className={cn("flex-1 min-h-0 flex flex-col", viewMode !== "timeline" && "hidden")}>
      <Timeline size="large" fill focusDate={focusDate} />
    </div>

    {/* Scheduler tab — week grid, full-bleed */}
    <div className={cn("flex-1 min-h-0 flex flex-col", viewMode !== "scheduler" && "hidden")}>
     <Scheduler size="large" fill />
    </div>

    {/* Calendar tab */}
    <div className={cn("flex-1 min-h-0 flex flex-col", viewMode !== "calendar" && "hidden")}>
     <FullScreenCalendar
      data={calendarData}
      onEventClick={handleCalendarEventClick}
     />
    </div>

    {/* Schedule & History tab — keeps the original 2-column layout but now
        as a scrollable panel filling the full content area. */}
    <div className={cn("flex-1 min-h-0 overflow-y-auto", viewMode !== "schedule" && "hidden")}>
     <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 pb-4">
      {/* Left: Upcoming Agenda */}
      <div className="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
       <div className="flex justify-between items-center mb-6">
        <h3 className="text-lg font-bold text-gray-800 flex items-center gap-2">
         <CalendarDays size={20} className="text-blue-500" />
         Upcoming Schedule
        </h3>
        <button
         onClick={() => setViewMode("calendar")}
         className="text-sm text-blue-600 hover:underline font-medium"
        >
         View Calendar
        </button>
       </div>

       <div className="space-y-1">
        {upcomingAppointments.map((event) => (
         <div
          key={event.id}
          className="flex gap-4 py-3 border-b border-slate-50 last:border-0 hover:bg-gray-50/50 transition-colors -mx-4 px-4 rounded-lg group"
         >
          <div className="flex flex-col items-center justify-start w-12 pt-1">
           <div className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-0.5">
            {format(new Date(event.date), "MMM")}
           </div>
           <div className="text-lg font-light text-gray-700 leading-none">
            {format(new Date(event.date), "dd")}
           </div>
          </div>

          <div className="flex-1 min-w-0">
           <div className="flex justify-between items-start mb-1">
            <div>
             <h4 className="font-medium text-gray-900 text-sm">
              {event.reason}
             </h4>
             <p className="text-xs text-gray-500 mt-0.5 line-clamp-1">
              {event.notes}
             </p>
            </div>
            <span className="text-[10px] px-2 py-0.5 rounded-full bg-gray-50 text-gray-500 border border-gray-100 uppercase tracking-wide font-medium shrink-0 ml-2">
             Appointment
            </span>
           </div>
           <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-4 text-[11px] text-gray-400">
             <span className="flex items-center gap-1.5">
              <Clock size={12} className="text-gray-300" />
              {event.time}
             </span>
             <span className="flex items-center gap-1.5">
              <User size={12} className="text-gray-300" />
              {event.doctor}
             </span>
            </div>
           </div>
          </div>
         </div>
        ))}

        {upcomingAppointments.length === 0 && (
         <div className="text-center py-10 text-gray-400">
          No upcoming appointments scheduled.
         </div>
        )}
       </div>
      </div>

      {/* Right: Quick History / Activity Feed */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
       <div className="flex justify-between items-center mb-6">
        <h3 className="text-lg font-bold text-gray-800 flex items-center gap-2">
         <CheckCircle2 size={20} className="text-emerald-500" />
         Recent History
        </h3>
       </div>

       <div className="relative border-l-2 border-gray-100/80 ml-2.5 space-y-6 pl-5 py-1">
        {pastAppointmentsAndTests.map((event) => (
         <div key={event.id} className="relative group">
          <div
           className={cn(
            "absolute -left-[27px] top-1.5 w-3 h-3 rounded-full border-[2px] bg-white transition-colors",
            event.type === "labs" ? "border-rose-400 group-hover:bg-rose-50"
            : event.type === "vaccinations" ? "border-purple-400 group-hover:bg-purple-50"
            : event.type === "imaging" ? "border-sky-400 group-hover:bg-sky-50"
            : "border-blue-400 group-hover:bg-blue-50"
           )}
          />
          <div>
           <div className="flex items-baseline gap-2 mb-0.5">
            <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wide">
             {format(new Date(event.date), "MMM d")}
            </span>
            {'time' in event && formatSpecificTime(event.time) && (
             <span className="text-[10px] text-gray-300">
              {formatSpecificTime(event.time)}
             </span>
            )}
           </div>
           <h4 className="text-sm font-medium text-gray-800 mb-0.5 group-hover:text-blue-600 transition-colors">
            {event.type === "appointments" ? (event as Appointment).reason
             : event.type === "vaccinations" ? (event as import('../types/medical').VaccinationEvent).name
             : event.type === "imaging" ? (event as ImagingEvent).name
             : (event as LabResult).testName}
           </h4>
           <p className="text-xs text-gray-500 leading-snug line-clamp-2">
           {event.type === "appointments" ? (event as Appointment).notes
             : event.type === "vaccinations" ? "Vaccination"
             : event.type === "imaging" ? (event as ImagingEvent).hospital
             : "Lab Test Results"}
           </p>
          </div>
         </div>
        ))}

        {pastAppointmentsAndTests.length === 0 && (
         <div className="text-center py-10 text-gray-400">
          No past events recorded.
         </div>
        )}
       </div>
      </div>
     </div>
    </div>
   </section>

   {/* Event Detail Modal (for calendar clicks) — fixed positioning, lives outside the layout */}
   {selectedCalendarEvent && (
    <>
     <div
      className="fixed inset-0 bg-gray-900/40 z-40 backdrop-blur-sm"
      onClick={() => setSelectedCalendarEvent(null)}
     />
     <div className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-2xl shadow-2xl z-50 w-[90%] max-w-md border border-gray-100">
      <EventPopoverContent 
        event={selectedCalendarEvent as DisplayedTimelineEvent} 
        onClose={() => setSelectedCalendarEvent(null)} 
      />
     </div>
    </>
   )}
  </div>
 );
}
