import React, { useCallback, useEffect, useState } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { ChevronDown, ChevronsUpDown, Map, FileText, Loader2, Users, FileCode, Clock } from 'lucide-react';
import { api } from '@/api';
import { APP_VERSION } from '@/lib/version';

/* ─── Priority lanes ────────────────────────────────────────────────────────── */

const PRIORITY_LANES = [
  { key: 'critical',   emoji: '🔴', label: 'CRITICAL',     borderColor: 'border-t-red-500',    textColor: 'text-red-500',    badgeClass: 'bg-red-500/15 text-red-500 border-red-500/20' },
  { key: 'high',       emoji: '🟠', label: 'HIGH',         borderColor: 'border-t-orange-500', textColor: 'text-orange-500', badgeClass: 'bg-orange-500/15 text-orange-500 border-orange-500/20' },
  { key: 'medium',     emoji: '🟡', label: 'MEDIUM',       borderColor: 'border-t-yellow-500', textColor: 'text-yellow-500', badgeClass: 'bg-yellow-500/15 text-yellow-500 border-yellow-500/20' },
  { key: 'low',        emoji: '🔵', label: 'LOW',          borderColor: 'border-t-blue-500',   textColor: 'text-blue-500',   badgeClass: 'bg-blue-500/15 text-blue-500 border-blue-500/20' },
  { key: 'niceToHave', emoji: '💭', label: 'NICE TO HAVE', borderColor: 'border-t-border',     textColor: 'text-muted-foreground', badgeClass: 'bg-muted/50 text-muted-foreground border-border/50' },
];

// Normalise any priority string to a lane key.
function laneForPriority(priority) {
  const normalised = String(priority || '').toLowerCase().replace(/[\s_-]+/g, '');
  const map = {
    critical:   'critical',
    high:       'high',
    medium:     'medium',
    low:        'low',
    nicetohave: 'niceToHave',
  };
  return map[normalised] ?? 'low';
}

/* ─── Roadmap item card ─────────────────────────────────────────────────────── */

function RoadmapItemCard({ item, defaultOpen }) {
  const lane = PRIORITY_LANES.find(l => l.key === laneForPriority(item.priority)) ?? PRIORITY_LANES[3];
  const [open, setOpen] = useState(defaultOpen);

  // Sync when parent toggles all cards via forceKey remount (no extra effect needed)
  return (
    <Collapsible open={open} onOpenChange={setOpen} className="group">
      <div className="rounded-xl border border-border/60 bg-card/90 transition-shadow hover:shadow-md overflow-hidden">

        {/* Trigger — always visible header */}
        <CollapsibleTrigger asChild>
          <button className="w-full text-left px-4 pt-3 pb-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
            <div className="flex items-start justify-between gap-2">
              <div className="flex-1 min-w-0">
                <Badge
                  variant="outline"
                  className={`${lane.badgeClass} border text-[11px] font-semibold px-1.5 py-0 mb-1.5`}
                >
                  {lane.emoji} {lane.label}
                </Badge>
                <p className="break-words text-sm font-semibold leading-snug">{item.title}</p>
              </div>
              <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground mt-0.5 transition-transform duration-200 group-data-[state=open]:rotate-180" />
            </div>
          </button>
        </CollapsibleTrigger>

        {/* Meta row — always visible */}
        {(item.added || item.addedBy || item.effort) && (
          <div className="px-4 pb-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
            {item.added && (
              <span className="flex items-center gap-1">
                <Clock className="h-3 w-3" />
                {item.added}
              </span>
            )}
            {item.addedBy && (
              <>
                <span aria-hidden="true">·</span>
                <span className="flex items-center gap-1">
                  <Users className="h-3 w-3" />
                  {item.addedBy}
                </span>
              </>
            )}
            {item.effort && (
              <>
                <span aria-hidden="true">·</span>
                <span>{item.effort}</span>
              </>
            )}
          </div>
        )}

        {/* Expandable detail */}
        <CollapsibleContent>
          <div className="px-4 pb-4 pt-1 space-y-3 border-t border-border/40">
            {item.description && (
              <div>
                <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1">Description</p>
                <p className="break-words text-sm leading-relaxed">{item.description}</p>
              </div>
            )}
            {item.rationale && (
              <div>
                <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1">Rationale</p>
                <p className="break-words text-sm leading-relaxed text-muted-foreground">{item.rationale}</p>
              </div>
            )}
            {item.implementationNotes && (
              <div>
                <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1">Implementation Notes</p>
                <div className="overflow-x-auto rounded-lg border border-border/50 bg-muted/50 p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap sm:text-sm">
                  {item.implementationNotes}
                </div>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </div>
    </Collapsible>
  );
}

/* ─── Priority lane column ──────────────────────────────────────────────────── */

function PriorityLane({ lane, items, defaultOpenCards, forceKey }) {
  if (items.length === 0) return null;

  return (
    <section aria-label={`${lane.label} priority`} className={`min-w-0 rounded-xl border border-border/60 border-t-4 ${lane.borderColor}`}>
      <div className="flex items-center gap-2 border-b border-border/50 px-4 py-2.5">
        <span aria-hidden="true">{lane.emoji}</span>
        <h3 className={`min-w-0 break-words text-xs font-bold uppercase tracking-wider ${lane.textColor}`}>{lane.label}</h3>
        <span className="ml-auto text-[11px] font-semibold text-muted-foreground tabular-nums">{items.length}</span>
      </div>
      <div className="p-3 space-y-2">
        {items.map(item => (
          <RoadmapItemCard key={`${item.id}-${forceKey}`} item={item} defaultOpen={defaultOpenCards} />
        ))}
      </div>
    </section>
  );
}

/* ─── Dev log entry ─────────────────────────────────────────────────────────── */

function DevLogEntry({ entry }) {
  const [open, setOpen] = useState(false);

  return (
    <Collapsible open={open} onOpenChange={setOpen} className="group">
      <div className="relative flex gap-4">
        <div className="flex flex-col items-center shrink-0">
          <div className="w-3 h-3 rounded-full bg-primary border-2 border-background mt-1.5" />
          <div className="w-px flex-1 bg-border/50" />
        </div>

        <div className="flex-1 pb-6 min-w-0">
          <CollapsibleTrigger asChild>
            <button className="w-full text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-lg">
              <div className="flex items-center gap-2 flex-wrap">
                <span className="font-mono font-bold text-sm">{entry.version}</span>
                {entry.date && <span className="text-xs text-muted-foreground">{entry.date}</span>}
                {entry.status && (
                  <Badge variant="outline" className={`text-[11px] ${
                    entry.status.includes('COMPLETED')
                      ? 'bg-emerald-500/15 text-emerald-500 border-emerald-500/20'
                      : 'bg-muted/50 text-muted-foreground border-border/50'
                  }`}>
                    {entry.status}
                  </Badge>
                )}
                {entry.filesModified?.length > 0 && (
                  <span className="text-xs text-muted-foreground flex items-center gap-0.5">
                    <FileCode className="h-3 w-3" />
                    {entry.filesModified.length} files
                  </span>
                )}
                <ChevronDown className="h-3.5 w-3.5 text-muted-foreground ml-auto transition-transform duration-200 group-data-[state=open]:rotate-180" />
              </div>
            </button>
          </CollapsibleTrigger>

          <CollapsibleContent>
            <div className="mt-3 space-y-3 pl-1">
              {entry.agents?.length > 0 && (
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-2">Agents</p>
                  <div className="flex flex-wrap gap-2">
                    {entry.agents.map((agent, idx) => (
                      <Badge key={idx} variant="outline" className={`text-[11px] ${
                        agent.status === 'COMPLETED'   ? 'bg-emerald-500/15 text-emerald-500 border-emerald-500/20' :
                        agent.status === 'IN PROGRESS' ? 'bg-yellow-500/15 text-yellow-500 border-yellow-500/20'   :
                        'bg-muted/50 text-muted-foreground border-border/50'
                      }`}>
                        {agent.status === 'COMPLETED' ? '✅' : agent.status === 'IN PROGRESS' ? '⏳' : '❓'}{' '}
                        {agent.name}{agent.time ? ` · ${agent.time}` : ''}
                      </Badge>
                    ))}
                  </div>
                </div>
              )}

              {entry.filesModified?.length > 0 && (
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5">Files Modified</p>
                  <div className="flex flex-wrap gap-1">
                    {entry.filesModified.map((file, idx) => (
                      <code key={idx} className="max-w-full break-all rounded border border-border/50 bg-muted/50 px-1.5 py-0.5 text-[11px] text-muted-foreground">
                        {file}
                      </code>
                    ))}
                  </div>
                </div>
              )}

              {entry.workCompleted?.length > 0 && (
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground mb-1.5">Work Completed</p>
                  <ul className="space-y-1">
                    {entry.workCompleted.map((work, idx) => (
                      <li key={idx} className="text-sm text-muted-foreground flex items-start gap-1.5">
                        <span className="text-emerald-500 mt-0.5 shrink-0">✓</span>
                        <span className="min-w-0 break-words">{work}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </CollapsibleContent>
        </div>
      </div>
    </Collapsible>
  );
}

/* ─── Main page ─────────────────────────────────────────────────────────────── */

export default function RoadmapPage() {
  const [roadmapData,   setRoadmapData]   = useState(null);
  const [devLogData,    setDevLogData]    = useState(null);
  const [roadmapLoading, setRoadmapLoading] = useState(true);
  const [devLogLoading,  setDevLogLoading]  = useState(false);
  const [roadmapError,  setRoadmapError]  = useState(null);
  const [devLogError,   setDevLogError]   = useState(null);

  // Expand/collapse all — forceKey causes cards to remount with the new default
  const [allExpanded, setAllExpanded] = useState(true);
  const [forceKey,    setForceKey]    = useState(0);

  const handleExpandToggle = () => {
    setAllExpanded(prev => !prev);
    setForceKey(prev => prev + 1);
  };

  const getIsDesktop = () => (
    typeof window !== 'undefined'
    && typeof window.matchMedia === 'function'
    && window.matchMedia('(min-width: 1024px)').matches
  );
  const [isDesktop, setIsDesktop] = useState(getIsDesktop);
  useEffect(() => {
    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return undefined;
    const mq = window.matchMedia('(min-width: 1024px)');
    const handler = (e) => setIsDesktop(e.matches);
    setIsDesktop(mq.matches);
    if (typeof mq.addEventListener === 'function') {
      mq.addEventListener('change', handler);
      return () => mq.removeEventListener('change', handler);
    }
    mq.addListener(handler);
    return () => mq.removeListener(handler);
  }, []);

  // Fetch roadmap on mount
  useEffect(() => {
    let cancelled = false;
    setRoadmapLoading(true);
    api.roadmap()
      .then(data => { if (!cancelled) setRoadmapData(data); })
      .catch(err  => { if (!cancelled) setRoadmapError(err.message || 'Failed to load roadmap'); })
      .finally(()  => { if (!cancelled) setRoadmapLoading(false); });
    return () => { cancelled = true; };
  }, []);

  // Lazy-load dev log when the Activity tab is first opened
  const fetchDevLog = useCallback(() => {
    if (devLogData || devLogLoading) return;
    let cancelled = false;
    setDevLogLoading(true);
    api.devLog()
      .then(data => { if (!cancelled) setDevLogData(data); })
      .catch(err  => { if (!cancelled) setDevLogError(err.message || 'Failed to load activity log'); })
      .finally(()  => { if (!cancelled) setDevLogLoading(false); });
  }, [devLogData, devLogLoading]);

  const version  = roadmapData?.version || APP_VERSION;
  const items    = roadmapData?.items   || [];
  const grouped  = PRIORITY_LANES.map(lane => ({
    ...lane,
    items: items.filter(item => laneForPriority(item.priority) === lane.key),
  }));
  const visibleLanes = grouped.filter(lane => lane.items.length > 0);
  const laneGridClass = {
    1: 'grid-cols-1',
    2: 'grid-cols-1 lg:grid-cols-2',
    3: 'grid-cols-1 sm:grid-cols-2 xl:grid-cols-3',
    4: 'grid-cols-1 sm:grid-cols-2 xl:grid-cols-4',
    5: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 min-[1400px]:grid-cols-5',
  }[visibleLanes.length] || 'grid-cols-1';

  const defaultOpenCards = isDesktop && allExpanded;
  const laneProps = { defaultOpenCards, forceKey };

  return (
    <div className="space-y-6">

      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex min-w-0 items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-border/70 bg-primary/10 text-primary">
            <Map className="h-5 w-5" />
          </div>
          <div className="min-w-0">
            <h1 className="text-2xl font-bold tracking-tight">Roadmap</h1>
            <p className="text-sm text-muted-foreground">Current and upcoming features by priority</p>
          </div>
        </div>
        <Badge variant="outline" className="font-mono text-sm self-start sm:self-auto">
          v{version}
        </Badge>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="roadmap" onValueChange={v => { if (v === 'activity') fetchDevLog(); }} className="min-w-0">
        <TabsList className="grid w-full grid-cols-2 sm:inline-flex sm:w-auto">
          <TabsTrigger value="roadmap" className="gap-1.5">
            <Map className="h-3.5 w-3.5" />
            Roadmap
          </TabsTrigger>
          <TabsTrigger value="activity" className="gap-1.5">
            <FileText className="h-3.5 w-3.5" />
            Activity Log
          </TabsTrigger>
        </TabsList>

        {/* ── Roadmap tab ── */}
        <TabsContent value="roadmap" className="mt-4">
          {roadmapLoading ? (
            <div className="flex items-center justify-center py-16 gap-3 text-muted-foreground">
              <Loader2 className="h-5 w-5 animate-spin" />
              <span className="text-sm">Loading roadmap…</span>
            </div>
          ) : roadmapError ? (
            <div className="rounded-xl border border-destructive/50 bg-destructive/5 py-8 text-center">
              <p className="text-destructive font-medium">Failed to load roadmap</p>
              <p className="text-sm text-muted-foreground mt-1">{roadmapError}</p>
            </div>
          ) : items.length === 0 ? (
            <div className="rounded-xl border border-dashed border-border/60 py-12 text-center text-sm text-muted-foreground">
              No roadmap items found.
            </div>
          ) : (
            <>
              <div className="flex justify-end mb-3">
                <Button variant="outline" size="sm" onClick={handleExpandToggle} className="gap-1.5">
                  <ChevronsUpDown className="h-3.5 w-3.5" />
                  {allExpanded ? 'Collapse All' : 'Expand All'}
                </Button>
              </div>

              {/* Size the board to its populated lanes so sparse roadmaps stay readable. */}
              <div className={`grid gap-4 ${laneGridClass}`}>
                {visibleLanes.map(lane => (
                  <PriorityLane key={lane.key} lane={lane} items={lane.items} {...laneProps} />
                ))}
              </div>
            </>
          )}
        </TabsContent>

        {/* ── Activity log tab ── */}
        <TabsContent value="activity" className="mt-4">
          {devLogLoading ? (
            <div className="flex items-center justify-center py-16 gap-3 text-muted-foreground">
              <Loader2 className="h-5 w-5 animate-spin" />
              <span className="text-sm">Loading activity log…</span>
            </div>
          ) : devLogError ? (
            <div className="rounded-xl border border-destructive/50 bg-destructive/5 py-8 text-center">
              <p className="text-destructive font-medium">Failed to load activity log</p>
              <p className="text-sm text-muted-foreground mt-1">{devLogError}</p>
            </div>
          ) : devLogData && devLogData.entries?.length === 0 ? (
            <div className="rounded-xl border border-dashed border-border/60 py-12 text-center text-sm text-muted-foreground">
              No activity log entries found.
            </div>
          ) : devLogData ? (
            <div className="pt-2">
              {devLogData.entries.map((entry, idx) => (
                <DevLogEntry key={entry.version || idx} entry={entry} />
              ))}
            </div>
          ) : null}
        </TabsContent>
      </Tabs>
    </div>
  );
}
