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 {
  AlertCircle,
  ChevronDown,
  CircleDot,
  Clock,
  ExternalLink,
  FileCode,
  FileText,
  Loader2,
  MessageCircle,
  RefreshCw,
} from 'lucide-react';
import { api } from '@/api';
import { errMessage } from '@/lib/utils';

/* ─── Types ──────────────────────────────────────────────────────────────── */

interface IssueLabel {
  id: number | string;
  name: string;
  color: string;
}

interface Issue {
  id: number | string;
  number: number;
  title: string;
  body?: string | null;
  html_url: string;
  created_at: string;
  comments?: number;
  labels?: IssueLabel[];
}

interface Lane {
  key: string;
  emoji: string;
  label: string;
  borderColor: string;
  textColor: string;
  badgeClass: string;
}

interface Agent {
  name?: string;
  status?: string;
  time?: string;
}

interface DevLogEntryData {
  version?: string;
  date?: string;
  status?: string;
  filesModified?: string[];
  agents?: Agent[];
  workCompleted?: string[];
}

interface RoadmapData {
  issues?: Issue[];
  fetchedAt?: string | null;
  stale?: boolean;
}

interface DevLogData {
  entries?: DevLogEntryData[];
}

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

const PRIORITY_LANES: Lane[] = [
  { 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' },
];

/* ─── Helpers ────────────────────────────────────────────────────────────── */

function priorityFromLabels(labels: IssueLabel[] = []): string {
  for (const l of labels) {
    if (l.name === 'priority:critical')     return 'critical';
    if (l.name === 'priority:high')         return 'high';
    if (l.name === 'priority:medium')       return 'medium';
    if (l.name === 'priority:low')          return 'low';
    if (l.name === 'priority:nice-to-have') return 'niceToHave';
  }
  return 'low';
}

function cleanTitle(title: string): string {
  return title.replace(/^(CRITICAL|HIGH|MEDIUM|LOW|NICE[\s-]TO[\s-]HAVE)\s*:\s*/i, '').trim();
}

function stripMarkdown(text?: string | null): string {
  if (!text) return '';
  return text
    .replace(/#{1,6}\s+[^\n]*/g, '')
    .replace(/```[\s\S]*?```/g, '')
    .replace(/`([^`]+)`/g, '$1')
    .replace(/\*\*([^*]+)\*\*/g, '$1')
    .replace(/\*([^*]+)\*/g, '$1')
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    .replace(/^[-*+]\s+/gm, '')
    .replace(/\n\n+/g, ' ')
    .replace(/\n/g, ' ')
    .replace(/\s{2,}/g, ' ')
    .trim();
}

function timeAgo(dateStr: string): string {
  const diff  = Date.now() - new Date(dateStr).getTime();
  const mins  = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days  = Math.floor(diff / 86400000);
  if (mins  <  1) return 'just now';
  if (mins  < 60) return `${mins}m ago`;
  if (hours < 24) return `${hours}h ago`;
  if (days  < 30) return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function labelStyle(hex: string): React.CSSProperties {
  const r = parseInt(hex.slice(0, 2), 16);
  const g = parseInt(hex.slice(2, 4), 16);
  const b = parseInt(hex.slice(4, 6), 16);
  return {
    backgroundColor: `rgba(${r},${g},${b},0.12)`,
    color:           `#${hex}`,
    border:          `1px solid rgba(${r},${g},${b},0.28)`,
  };
}

/* ─── Label chip ─────────────────────────────────────────────────────────── */

function LabelChip({ label }: { label: IssueLabel }) {
  return (
    <span
      style={labelStyle(label.color)}
      className="rounded-full px-2 py-0.5 text-[10px] font-semibold leading-none whitespace-nowrap"
    >
      {label.name}
    </span>
  );
}

/* ─── Issue card ─────────────────────────────────────────────────────────── */

function IssueCard({ issue }: { issue: Issue }) {
  const typeLabels = issue.labels || [];
  const title      = cleanTitle(issue.title);
  const preview    = stripMarkdown(issue.body);

  return (
    <a
      href={issue.html_url}
      target="_blank"
      rel="noopener noreferrer"
      className="block rounded-xl border border-border/60 bg-card hover:shadow-md hover:-translate-y-0.5 transition-all duration-150 overflow-hidden group focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
      aria-label={`Issue #${issue.number}: ${title}`}
    >
      {/* Title row */}
      <div className="px-4 pt-3 pb-1.5 flex items-start gap-3">
        <p className="flex-1 min-w-0 text-sm font-semibold leading-snug break-words">
          {title}
        </p>
        <span className="shrink-0 font-mono text-[11px] text-muted-foreground/60 mt-px tabular-nums">
          #{issue.number}
        </span>
      </div>

      {/* Body preview */}
      {preview && (
        <p className="px-4 pb-2.5 text-xs text-muted-foreground line-clamp-2 leading-relaxed">
          {preview}
        </p>
      )}

      {/* Type labels */}
      {typeLabels.length > 0 && (
        <div className="px-4 pb-3 flex flex-wrap gap-1.5">
          {typeLabels.map(label => (
            <LabelChip key={label.id} label={label} />
          ))}
        </div>
      )}

      {/* Footer */}
      <div className="px-4 py-2 flex items-center justify-between border-t border-border/40 text-[11px] text-muted-foreground">
        <div className="flex items-center gap-3">
          <span className="flex items-center gap-1">
            <Clock className="h-3 w-3 shrink-0" />
            {timeAgo(issue.created_at)}
          </span>
          {(issue.comments ?? 0) > 0 && (
            <span className="flex items-center gap-1">
              <MessageCircle className="h-3 w-3 shrink-0" />
              {issue.comments}
            </span>
          )}
        </div>
        <ExternalLink className="h-3 w-3 opacity-0 group-hover:opacity-50 transition-opacity" />
      </div>
    </a>
  );
}

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

function PriorityLane({ lane, items }: { lane: Lane; items: Issue[] }) {
  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 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(issue => (
          <IssueCard key={issue.id} issue={issue} />
        ))}
      </div>
    </section>
  );
}

/* ─── Stats bar ──────────────────────────────────────────────────────────── */

function StatsBar({ issues, fetchedAt, stale, onRefresh, refreshing }: {
  issues: Issue[];
  fetchedAt?: string | null;
  stale?: boolean;
  onRefresh: () => void;
  refreshing: boolean;
}) {
  const counts: Record<string, number> = Object.fromEntries(PRIORITY_LANES.map(l => [l.key, 0]));
  issues.forEach(issue => {
    const p = priorityFromLabels(issue.labels);
    counts[p] = (counts[p] || 0) + 1;
  });
  const nonEmpty = PRIORITY_LANES.filter(l => (counts[l.key] ?? 0) > 0);

  return (
    <div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-border/60 bg-muted/30 px-4 py-3 text-[12px]">
      <span className="font-semibold">{issues.length} open</span>

      {nonEmpty.map(lane => (
        <React.Fragment key={lane.key}>
          <span className="text-border/60" aria-hidden>·</span>
          <span className={`flex items-center gap-1.5 ${lane.textColor}`}>
            <span aria-hidden>{lane.emoji}</span>
            <span className="font-semibold tabular-nums">{counts[lane.key]}</span>
            <span className="text-muted-foreground font-normal">{lane.label}</span>
          </span>
        </React.Fragment>
      ))}

      <div className="ml-auto flex items-center gap-2 text-muted-foreground">
        {fetchedAt && (
          <span className="text-[11px]">
            {stale && <span className="text-yellow-500 mr-1">⚠ stale ·</span>}
            {timeAgo(fetchedAt)}
          </span>
        )}
        <Button
          variant="ghost"
          size="icon"
          className="h-6 w-6"
          onClick={onRefresh}
          disabled={refreshing}
          title="Refresh issues"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />
        </Button>
      </div>
    </div>
  );
}

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

function DevLogEntry({ entry }: { entry: DevLogEntryData }) {
  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) > 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) > 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) > 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) > 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<RoadmapData | null>(null);
  const [devLogData,       setDevLogData]       = useState<DevLogData | null>(null);
  const [roadmapLoading,   setRoadmapLoading]   = useState(true);
  const [roadmapRefreshing,setRoadmapRefreshing]= useState(false);
  const [devLogLoading,    setDevLogLoading]    = useState(false);
  const [roadmapError,     setRoadmapError]     = useState<string | null>(null);
  const [devLogError,      setDevLogError]      = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    setRoadmapLoading(true);
    api.roadmap()
      .then(data => { if (!cancelled) setRoadmapData(data as RoadmapData); })
      .catch(err  => { if (!cancelled) setRoadmapError(errMessage(err, 'Failed to load issues')); })
      .finally(()  => { if (!cancelled) setRoadmapLoading(false); });
    return () => { cancelled = true; };
  }, []);

  const handleRefresh = () => {
    setRoadmapRefreshing(true);
    api.roadmap(true)
      .then(data => setRoadmapData(data as RoadmapData))
      .catch(() => {})
      .finally(() => setRoadmapRefreshing(false));
  };

  const fetchDevLog = useCallback(() => {
    if (devLogData || devLogLoading) return;
    let cancelled = false;
    setDevLogLoading(true);
    api.devLog()
      .then(data => { if (!cancelled) setDevLogData(data as DevLogData); })
      .catch(err  => { if (!cancelled) setDevLogError(errMessage(err, 'Failed to load activity log')); })
      .finally(()  => { if (!cancelled) setDevLogLoading(false); });
    return () => { cancelled = true; };
  }, [devLogData, devLogLoading]);

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

  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">
            <CircleDot className="h-5 w-5" />
          </div>
          <div className="min-w-0">
            <h1 className="text-2xl font-bold tracking-tight">Issues & Roadmap</h1>
            <p className="text-sm text-muted-foreground">
              Open issues ·{' '}
              <a
                href="https://dream.scheller.ltd/null/BillTracker/issues"
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary hover:underline underline-offset-4"
              >
                BillTracker ↗
              </a>
            </p>
          </div>
        </div>
        {issues.length > 0 && (
          <Badge variant="outline" className="font-mono text-sm self-start sm:self-auto">
            {issues.length} open
          </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">
            <CircleDot className="h-3.5 w-3.5" />
            Issues
          </TabsTrigger>
          <TabsTrigger value="activity" className="gap-1.5">
            <FileText className="h-3.5 w-3.5" />
            Activity Log
          </TabsTrigger>
        </TabsList>

        {/* ── Issues 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 issues…</span>
            </div>
          ) : roadmapError ? (
            <div className="rounded-xl border border-destructive/50 bg-destructive/5 py-8 text-center space-y-2">
              <div className="flex items-center justify-center gap-2 text-destructive font-medium">
                <AlertCircle className="h-4 w-4" />
                Failed to load issues
              </div>
              <p className="text-sm text-muted-foreground">{roadmapError}</p>
            </div>
          ) : issues.length === 0 ? (
            <div className="rounded-xl bg-muted/20 py-12 text-center text-sm text-muted-foreground">
              No open issues.
            </div>
          ) : (
            <div className="space-y-4">
              <StatsBar
                issues={issues}
                fetchedAt={roadmapData?.fetchedAt}
                stale={roadmapData?.stale}
                onRefresh={handleRefresh}
                refreshing={roadmapRefreshing}
              />
              <div className={`grid gap-4 ${laneGridClass}`}>
                {visibleLanes.map(lane => (
                  <PriorityLane key={lane.key} lane={lane} items={lane.items} />
                ))}
              </div>
            </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 bg-muted/20 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>
  );
}
