import React, { useCallback, useEffect, useState } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
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 Configuration ───────────────────────────── */

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

function laneForPriority(priority) {
  const key = typeof priority === 'string'
    ? priority.toLowerCase().replace(/\s+/g, '').replace(/to/ig, 'To')
    : '';
  // Map API priority keys to lane keys
  const mapping = {
    critical: 'critical',
    high: 'high',
    medium: 'medium',
    low: 'low',
    nicetohave: 'niceToHave',
    'nice to have': 'niceToHave',
  };
  return mapping[key] || 'low';
}

/* ─── Roadmap Item Card ────────────────────────────────── */

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

  const handleOpenChange = useCallback((value) => {
    setOpen(value);
    onToggle?.(value);
  }, [onToggle]);

  const effortLabel = item.effort || '';

  return (
    <Collapsible open={open} onOpenChange={handleOpenChange} className="group">
      <Card className="border-border/70 bg-card/95 transition-shadow hover:shadow-md">
        <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-2xl">
            <CardHeader className="pb-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`}
                    aria-label={`${lane.label} priority`}
                  >
                    {lane.emoji} {lane.label}
                  </Badge>
                  <h4 className="font-semibold text-sm leading-snug line-clamp-3">
                    {item.title}
                  </h4>
                </div>
                <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 group-aria-expanded:rotate-180 mt-0.5" />
              </div>
            </CardHeader>
          </button>
        </CollapsibleTrigger>

        <div className="px-6 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-0.5">
              <Clock className="h-3 w-3" />
              {item.added}
            </span>
          )}
          {item.addedBy && (
            <>
              <span aria-hidden="true">·</span>
              <span className="flex items-center gap-0.5">
                <Users className="h-3 w-3" />
                {item.addedBy}
              </span>
            </>
          )}
          {effortLabel && (
            <>
              <span aria-hidden="true">·</span>
              <span className="flex items-center gap-0.5">
                <Clock className="h-3 w-3" />
                {effortLabel}
              </span>
            </>
          )}
        </div>

        <CollapsibleContent>
          <CardContent className="pt-0 pb-4 space-y-3">
            {item.description && (
              <div>
                <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1">Description</p>
                <p className="text-sm leading-relaxed">{item.description}</p>
              </div>
            )}
            {item.rationale && (
              <div>
                <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1">Rationale</p>
                <p className="text-sm leading-relaxed text-muted-foreground">{item.rationale}</p>
              </div>
            )}
            {item.implementationNotes && (
              <div>
                <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1">Implementation Notes</p>
                <div className="rounded-xl bg-muted/50 border border-border/50 p-3 text-sm font-mono leading-relaxed whitespace-pre-wrap">
                  {item.implementationNotes}
                </div>
              </div>
            )}
          </CardContent>
        </CollapsibleContent>
      </Card>
    </Collapsible>
  );
}

/* ─── Priority Lane ─────────────────────────────────────── */

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

  return (
    <section
      role="region"
      aria-label={`${lane.label} priority lane`}
      className={`rounded-2xl border ${lane.borderColor} border-t-4 bg-background/50`}
    >
      <div className="px-4 py-3 flex items-center gap-2 border-b border-border/50">
        <span className="text-lg" aria-hidden="true">{lane.emoji}</span>
        <h3 className={`font-bold text-sm ${lane.textColor}`}>{lane.label}</h3>
        <Badge variant="secondary" className="ml-auto text-[11px]">{items.length}</Badge>
      </div>
      <div className="p-3 space-y-3">
        {items.map((item) => (
          <RoadmapItemCard key={item.id} 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">
        {/* Timeline line */}
        <div className="flex flex-col items-center">
          <div className="w-3 h-3 rounded-full bg-primary border-2 border-background shrink-0 mt-1.5" />
          <div className="w-px flex-1 bg-border/70" />
        </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-xl">
              <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-600 dark:text-emerald-400 border-emerald-500/20'
                        : 'bg-muted/50 text-muted-foreground'
                    }`}
                  >
                    {entry.status}
                  </Badge>
                )}
                {entry.agents?.length > 0 && (
                  <span className="text-xs text-muted-foreground">
                    {entry.agents.map(a => a.name).join(', ')}
                  </span>
                )}
                {(entry.filesModified?.length > 0 || entry.workCompleted?.length > 0) && (
                  <span className="text-xs text-muted-foreground">
                    <FileCode className="inline h-3 w-3 mr-0.5" />
                    {entry.filesModified?.length || 0} files
                  </span>
                )}
                <ChevronDown className="h-3.5 w-3.5 text-muted-foreground transition-transform duration-200 group-aria-expanded:rotate-180 ml-auto" />
              </div>
            </button>
          </CollapsibleTrigger>

          <CollapsibleContent>
            <div className="mt-3 space-y-3">
              {entry.agents?.length > 0 && (
                <div>
                  <p className="text-xs font-semibold uppercase tracking-wide 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-600 dark:text-emerald-400 border-emerald-500/20'
                            : agent.status === 'IN PROGRESS'
                              ? 'bg-yellow-500/15 text-yellow-600 dark:text-yellow-400 border-yellow-500/20'
                              : 'bg-muted/50 text-muted-foreground'
                        }`}
                      >
                        {agent.status === 'COMPLETED' ? '✅' : agent.status === 'IN PROGRESS' ? '⏳' : '❓'}{' '}
                        {agent.name}
                        {agent.time ? ` · ${agent.time}` : ''}
                      </Badge>
                    ))}
                  </div>
                </div>
              )}

              {entry.filesModified?.length > 0 && (
                <div>
                  <p className="text-xs font-semibold uppercase tracking-wide 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="text-[11px] bg-muted/50 px-1.5 py-0.5 rounded border border-border/50 text-muted-foreground">
                        {file}
                      </code>
                    ))}
                  </div>
                </div>
              )}

              {entry.workCompleted?.length > 0 && (
                <div>
                  <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1.5">Work Completed</p>
                  <ul className="space-y-0.5">
                    {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>
                        {work}
                      </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);
  const [allExpanded, setAllExpanded] = useState(true);

  // Detect desktop for default expand state
  const [isDesktop, setIsDesktop] = useState(
    typeof window !== 'undefined' ? window.matchMedia('(min-width: 1024px)').matches : true
  );

  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const handler = (e) => setIsDesktop(e.matches);
    mq.addEventListener('change', handler);
    setIsDesktop(mq.matches);
    return () => mq.removeEventListener('change', 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; };
  }, []);

  const fetchDevLog = useCallback(() => {
    if (devLogData) return; // Already loaded
    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);
      });
    return () => { cancelled = true; };
  }, [devLogData]);

  const version = roadmapData?.version || APP_VERSION;
  const items = roadmapData?.items || [];
  const counts = roadmapData?.counts || {};
  const devLogEntries = devLogData?.entries || [];

  // Group items by priority lane
  const grouped = PRIORITY_LANES.map(lane => ({
    ...lane,
    items: items.filter(item => laneForPriority(item.priority) === lane.key),
  }));

  const defaultOpenCards = isDesktop && allExpanded;

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex 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>
            <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={(value) => { if (value === 'activity') fetchDevLog(); }}>
        <TabsList>
          <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">
          {roadmapLoading ? (
            <div className="flex items-center justify-center py-16">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              <span className="ml-3 text-muted-foreground">Loading roadmap…</span>
            </div>
          ) : roadmapError ? (
            <Card className="border-destructive/50 bg-destructive/5">
              <CardContent className="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>
              </CardContent>
            </Card>
          ) : items.length === 0 ? (
            <Card>
              <CardContent className="py-12 text-center text-muted-foreground">
                No roadmap items found.
              </CardContent>
            </Card>
          ) : (
            <>
              {/* Expand/Collapse All toggle */}
              <div className="flex justify-end mb-3">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setAllExpanded(prev => !prev)}
                  className="gap-1.5"
                >
                  <ChevronsUpDown className="h-3.5 w-3.5" />
                  {allExpanded ? 'Collapse All' : 'Expand All'}
                </Button>
              </div>

              {/* Desktop: 5-column grid */}
              <div className="hidden lg:grid lg:grid-cols-5 gap-4">
                {grouped.map(lane => (
                  <PriorityLane key={lane.key} lane={lane} items={lane.items} defaultOpenCards={defaultOpenCards} />
                ))}
              </div>

              {/* Tablet: 2-column grid */}
              <div className="hidden sm:grid sm:grid-cols-2 lg:hidden gap-4">
                {/* Left column: Critical + High */}
                <div className="space-y-4">
                  {grouped.filter(l => l.key === 'critical' || l.key === 'high').map(lane => (
                    <PriorityLane key={lane.key} lane={lane} items={lane.items} defaultOpenCards={defaultOpenCards} />
                  ))}
                </div>
                {/* Right column: Medium + Low + Nice to Have */}
                <div className="space-y-4">
                  {grouped.filter(l => l.key === 'medium' || l.key === 'low' || l.key === 'niceToHave').map(lane => (
                    <PriorityLane key={lane.key} lane={lane} items={lane.items} defaultOpenCards={defaultOpenCards} />
                  ))}
                </div>
              </div>

              {/* Mobile: single column */}
              <div className="sm:hidden space-y-4">
                {grouped.map(lane => (
                  <PriorityLane key={lane.key} lane={lane} items={lane.items} defaultOpenCards={defaultOpenCards} />
                ))}
              </div>
            </>
          )}
        </TabsContent>

        {/* ─── Activity Log Tab ─── */}
        <TabsContent value="activity">
          {devLogLoading ? (
            <div className="flex items-center justify-center py-16">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              <span className="ml-3 text-muted-foreground">Loading activity log…</span>
            </div>
          ) : devLogError ? (
            <Card className="border-destructive/50 bg-destructive/5">
              <CardContent className="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>
              </CardContent>
            </Card>
          ) : devLogEntries.length === 0 ? (
            <Card>
              <CardContent className="py-12 text-center text-muted-foreground">
                No activity log entries found.
              </CardContent>
            </Card>
          ) : (
            <div className="pt-2">
              {devLogEntries.map((entry, idx) => (
                <DevLogEntry key={entry.version || idx} entry={entry} />
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}