import { useState, useEffect, useCallback, type ReactNode, type MouseEvent } from 'react';
import { useParams, Link } from 'react-router';
import {
  Search,
  CheckCircle2,
  AlertCircle,
  Clock,
  Loader2,
  StopCircle,
  AlertTriangle,
  Inbox,
  Square,
  Trash2,
  Bell,
} from 'lucide-react';
import { WorkspaceLayout } from 'officerdev';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { useClient } from 'hooks/useClient';
import { toast } from 'sonner';
import { useDashboardState } from 'state/useDashboardState';
import { Card } from '@/components/Card';
import { ScriptJobDetail } from './ScriptJobDetail';
import { DownloadJobDetail } from './DownloadJobDetail';
import { PipelineJobDetail } from './JobDetail';

type JobSummary = {
  id: string;
  mode: string;
  taskDirName: string;
  taskName: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'interrupted';
  exitCode: number | null;
  target: string | null;
  totalCost: { inputTokens: number; outputTokens: number; totalUSD: number } | null;
  createdAt: string;
  error: string | null;
};

const basename = (p: string | null) => (p ? p.replace(/\/+$/, '').split('/').pop() || p : null);

const formatDate = (iso: string) =>
  new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });

const StatusIcon = ({ status }: { status: JobSummary['status'] }) => {
  switch (status) {
    case 'completed':
      return <CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />;
    case 'failed':
      return <AlertCircle className="h-4 w-4 text-red-500 shrink-0" />;
    case 'running':
      return <Loader2 className="h-4 w-4 text-blue-500 shrink-0 animate-spin" />;
    case 'stopped':
      return <StopCircle className="h-4 w-4 text-amber-500 shrink-0" />;
    case 'interrupted':
      return <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />;
    case 'pending':
      return <Clock className="h-4 w-4 text-duck-dark/40 shrink-0" />;
  }
};

// Jobs data — each list panel polls independently (cheap for a single user).
const useJobsData = () => {
  const client = useClient();
  const [jobs, setJobs] = useState<JobSummary[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const load = useCallback(
    () =>
      client
        .get<JobSummary[]>('/jobs')
        .then((d) => {
          setJobs(d);
          setIsLoading(false);
        })
        .catch(() => setIsLoading(false)),
    [client],
  );
  useEffect(() => {
    load();
    const timer = setInterval(load, 2500);
    return () => clearInterval(timer);
  }, [load]);
  // Running → stop; queued/finished → delete the row. Then refresh.
  const act = useCallback(
    (ev: MouseEvent, job: JobSummary) => {
      ev.stopPropagation();
      const req = job.status === 'running' ? client.post(`/jobs/${job.id}/stop`, {}) : client.delete(`/jobs/${job.id}`);
      req.then(() => load()).catch(() => {});
    },
    [client, load],
  );
  const clearHistory = useCallback(() => {
    client
      .delete('/jobs/history')
      .then(() => load())
      .catch(() => {});
  }, [client, load]);
  return { jobs, isLoading, act, clearHistory };
};

type JobRowProps = { job: JobSummary; onAction: (ev: MouseEvent, job: JobSummary) => void };
const JobRow = ({ job, onAction }: JobRowProps) => {
  const { id: activeId } = useParams<{ id: string }>();
  const isRunning = job.status === 'running';
  const target = basename(job.target);
  return (
    <div
      className={`group w-full border-b border-duck-dark/5 flex items-center transition-colors ${job.id === activeId ? 'bg-duck-teal/10' : 'hover:bg-duck-dark/5'}`}
    >
      <Link
        to={`/jobs/${job.id}`}
        className="flex-1 min-w-0 text-left px-4 py-2.5 flex items-center gap-3 cursor-pointer"
      >
        <StatusIcon status={job.status} />
        <div className="flex-1 min-w-0">
          <span className="text-sm font-medium text-duck-dark truncate block">{job.taskName}</span>
          {target && (
            <span className="text-xs text-duck-dark/60 truncate block" title={job.target ?? undefined}>
              {target}
            </span>
          )}
          <div className="flex items-center gap-2 mt-0.5">
            <span className="text-xs text-duck-dark/40">{formatDate(job.createdAt)}</span>
            {job.error && <span className="text-xs text-red-500 truncate max-w-[160px]">{job.error}</span>}
          </div>
        </div>
      </Link>
      <button
        onClick={(ev) => onAction(ev, job)}
        title={isRunning ? 'Stop' : 'Delete'}
        className="shrink-0 mr-2 p-1.5 rounded-md text-duck-dark/40 hover:text-red-500 hover:bg-red-500/10 md:opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
      >
        {isRunning ? <Square className="h-4 w-4" /> : <Trash2 className="h-4 w-4" />}
      </button>
    </div>
  );
};

const PanelHeader = ({ children }: { children: ReactNode }) => (
  <div className="px-3 py-2 border-b border-duck-dark/10 flex items-center gap-2 shrink-0">{children}</div>
);

// Top-left panel: running first, then the FIFO queue (oldest pending on top — next to run).
// TEMPORARY. The first producer for officer-notify, so the pipe can be exercised from the UI before any
// real event is wired to it. Sends { type: 'test' }, which reaches every configured channel — Discord
// today, APNs and FCM once their credentials exist. Delete this once a real producer replaces it.
const TestNotificationButton = () => {
  const client = useClient();
  const [sending, setSending] = useState(false);

  const send = async () => {
    setSending(true);
    try {
      // userId is omitted deliberately: the sidecar takes it from the header the proxy injects.
      const res = await client.post<{ results?: { channel: string; sent: number; failed: number }[] }>(
        '/notify/_officer/notify',
        { type: 'test' },
      );
      const results = res?.results ?? [];
      if (results.length === 0) {
        toast.warning('No channels configured');
      } else {
        toast.success(results.map((r) => `${r.channel}: ${r.sent} sent`).join(', '));
      }
    } catch {
      toast.error('Failed to send notification');
    } finally {
      setSending(false);
    }
  };

  return (
    <button
      onClick={send}
      disabled={sending}
      title="Send a test notification to every configured channel"
      className="ml-auto shrink-0 flex items-center gap-1 text-xs font-medium text-duck-dark/50 hover:text-duck-teal cursor-pointer disabled:opacity-40"
    >
      <Bell className="h-3.5 w-3.5" />
      {sending ? 'Sending…' : 'Test notify'}
    </button>
  );
};

const ActiveJobsPanel = () => {
  const { jobs, isLoading, act } = useJobsData();
  const active = [
    ...jobs.filter((j) => j.status === 'running'),
    ...jobs.filter((j) => j.status === 'pending').sort((a, b) => +new Date(a.createdAt) - +new Date(b.createdAt)),
  ];
  return (
    <div className="h-full p-2">
      <Card className="h-full flex flex-col overflow-hidden">
        <PanelHeader>
          <h2 className="text-sm font-semibold text-duck-dark">Running &amp; Queued</h2>
          {active.length > 0 && <span className="text-xs text-duck-dark/40">{active.length}</span>}
          <TestNotificationButton />
        </PanelHeader>
        <div className="flex-1 overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">Loading…</div>
          ) : active.length === 0 ? (
            <div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">Nothing running</div>
          ) : (
            active.map((job) => <JobRow key={job.id} job={job} onAction={act} />)
          )}
        </div>
      </Card>
    </div>
  );
};

// Bottom-left panel: finished / failed / stopped, newest first, searchable.
const HistoryJobsPanel = () => {
  const { jobs, isLoading, act, clearHistory } = useJobsData();
  const [search, setSearch] = useState('');
  const history = jobs
    .filter((j) => j.status !== 'running' && j.status !== 'pending')
    .filter((j) => {
      if (!search) return true;
      const q = search.toLowerCase();
      return j.taskName.toLowerCase().includes(q) || j.taskDirName.toLowerCase().includes(q) || j.status.includes(q);
    });
  return (
    <div className="h-full p-2">
      <Card className="h-full flex flex-col overflow-hidden">
        <PanelHeader>
          <h2 className="text-sm font-semibold text-duck-dark shrink-0">History</h2>
          <div className="relative flex-1">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-duck-dark/40" />
            <input
              type="text"
              placeholder="Search…"
              value={search}
              onChange={(ev) => setSearch(ev.target.value)}
              className="w-full pl-8 pr-3 py-1 text-sm rounded-md border border-duck-dark/15 bg-background/60 text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-1 focus:ring-duck-teal/40"
            />
          </div>
          {history.length > 0 && (
            <button
              onClick={clearHistory}
              title="Delete all finished jobs"
              className="shrink-0 text-xs font-medium text-duck-dark/50 hover:text-red-500 cursor-pointer"
            >
              Clear all
            </button>
          )}
        </PanelHeader>
        <div className="flex-1 overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">Loading…</div>
          ) : history.length === 0 ? (
            <div className="flex items-center justify-center h-full text-duck-dark/30 text-xs">
              {search ? 'No matches' : 'No finished jobs'}
            </div>
          ) : (
            history.map((job) => <JobRow key={job.id} job={job} onAction={act} />)
          )}
        </div>
      </Card>
    </div>
  );
};

// ── Right panel: the selected job's detail, by mode (script terminal / pipeline steps) ──
const JobDetailPanel = () => {
  const { id } = useParams<{ id: string }>();
  const client = useClient();
  const [mode, setMode] = useState<string | null>(null);

  useEffect(() => {
    if (!id) {
      setMode(null);
      return;
    }
    setMode(null);
    client
      .get<{ mode?: string }>(`/jobs/${id}`)
      .then((j) => setMode(j.mode ?? 'pipeline'))
      .catch(() => setMode('notfound'));
  }, [id]);

  if (!id) {
    return (
      <div className="h-full p-2">
        <Card className="h-full flex flex-col items-center justify-center gap-2 text-duck-dark/30">
          <Inbox className="h-8 w-8" />
          <span className="text-sm">Select a job</span>
        </Card>
      </div>
    );
  }
  if (mode === null) {
    return (
      <div className="h-full p-2">
        <Card className="h-full flex items-center justify-center text-duck-dark/40">
          <Loader2 className="h-5 w-5 animate-spin" />
        </Card>
      </div>
    );
  }
  if (mode === 'notfound') {
    return (
      <div className="h-full p-2">
        <Card className="h-full flex items-center justify-center text-duck-dark/50 text-sm">Job not found.</Card>
      </div>
    );
  }
  // Pipeline detail brings its own full chrome; the script terminal + download progress get a card here.
  if (mode === 'script') {
    return (
      <div className="h-full p-2">
        <Card className="h-full flex flex-col overflow-hidden">
          <ScriptJobDetail key={id} />
        </Card>
      </div>
    );
  }
  if (mode === 'download') {
    return (
      <div className="h-full p-2">
        <Card className="h-full flex flex-col overflow-hidden">
          <DownloadJobDetail key={id} />
        </Card>
      </div>
    );
  }
  return <PipelineJobDetail key={id} />;
};

// Left column = two stacked panels (Active over History) with a resizable divider, like /email's
// reader/chat split. Right column = the detail.
const JOBS_LAYOUT: LayoutNode = {
  type: 'group',
  id: 'jobs-root',
  direction: 'horizontal',
  children: [
    {
      node: {
        type: 'group',
        id: 'jobs-left',
        direction: 'vertical',
        children: [
          { node: { type: 'panel', id: 'jobs-active', appType: null }, size: 68 },
          { node: { type: 'panel', id: 'jobs-history', appType: null }, size: 32 },
        ],
      },
      size: 32,
    },
    { node: { type: 'panel', id: 'job-detail', appType: null }, size: 68 },
  ],
};

const PANEL_COMPONENTS: PanelComponents = {
  'jobs-active': ActiveJobsPanel,
  'jobs-history': HistoryJobsPanel,
  'job-detail': JobDetailPanel,
};

// Guard the persisted layout against a stale shape (e.g. panel ids changed in a later build): the panels
// render from PANEL_COMPONENTS by id, so a layout whose panel ids don't match ours would render blanks.
// If it doesn't line up exactly, fall back to the default rather than trust the saved node.
const collectPanelIds = (node: LayoutNode, acc: Set<string>): Set<string> => {
  if (node.type === 'panel') acc.add(node.id);
  else for (const child of node.children) collectPanelIds(child.node, acc);
  return acc;
};

const matchesPanelSet = (node: LayoutNode): boolean => {
  const ids = collectPanelIds(node, new Set<string>());
  const expected = Object.keys(PANEL_COMPONENTS);
  return ids.size === expected.length && expected.every((id) => ids.has(id));
};

// One page for /jobs and /jobs/:id — master (list) + detail, resizable like /chat. The layout is
// persisted per-user via useDashboardState (screens/ namespace), so pane sizes survive reloads.
// Wait for isLoaded before mounting: ResizablePanel reads defaultSize only at mount, so mounting
// during the query's loading window would freeze the fallback sizes and ignore the persisted layout
// that arrives after (the "survives nav but not refresh" bug — on nav the query is already cached).
export const JobsPage = () => {
  const { value, setValue, isLoaded } = useDashboardState<LayoutNode>('screens/jobs', JOBS_LAYOUT);
  if (!isLoaded) return <div className="h-full w-full" />;
  const layout = matchesPanelSet(value) ? value : JOBS_LAYOUT;
  return (
    <div className="h-full w-full">
      <WorkspaceLayout layout={layout} onLayoutChange={setValue} components={PANEL_COMPONENTS} noHeader />
    </div>
  );
};
