import { useState, useEffect, useCallback, type ReactNode, type MouseEvent } from 'react';
import { useParams, useNavigate } from 'react-router';
import { Search, CheckCircle2, AlertCircle, Clock, Loader2, StopCircle, AlertTriangle, Inbox, X } from 'lucide-react';
import { WorkspaceLayout } from 'officerdev';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { useClient } from 'hooks/useClient';
import { Card } from '@/components/Card';
import { ScriptJobDetail } from './ScriptJobDetail';
import { PipelineJobDetail } from './JobDetail';

type JobSummary = {
  id: string;
  mode: string;
  taskDirName: string;
  taskName: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'interrupted';
  exitCode: number | null;
  totalCost: { inputTokens: number; outputTokens: number; totalUSD: number } | null;
  createdAt: string;
  error: string | 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]);
  const cancel = useCallback(
    (ev: MouseEvent, id: string) => { ev.stopPropagation(); client.post(`/jobs/${id}/stop`, {}).then(() => load()).catch(() => {}); },
    [client, load],
  );
  return { jobs, isLoading, cancel };
};

type JobRowProps = { job: JobSummary; onCancel: (ev: MouseEvent, id: string) => void };
const JobRow = ({ job, onCancel }: JobRowProps) => {
  const navigate = useNavigate();
  const { id: activeId } = useParams<{ id: string }>();
  const cancellable = job.status === 'running' || job.status === 'pending';
  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'}`}>
      <button onClick={() => navigate(`/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>
          <div className="flex items-center gap-2 mt-0.5">
            <span className="text-xs text-duck-dark/50">{formatDate(job.createdAt)}</span>
            {job.error && <span className="text-xs text-red-500 truncate max-w-[180px]">{job.error}</span>}
          </div>
        </div>
      </button>
      {cancellable && (
        <button
          onClick={(ev) => onCancel(ev, job.id)}
          title={job.status === 'pending' ? 'Remove from queue' : 'Stop'}
          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"
        >
          <X 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).
const ActiveJobsPanel = () => {
  const { jobs, isLoading, cancel } = 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>}
        </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} onCancel={cancel} />)
          )}
        </div>
      </Card>
    </div>
  );
};

// Bottom-left panel: finished / failed / stopped, newest first, searchable.
const HistoryJobsPanel = () => {
  const { jobs, isLoading, cancel } = 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>
        </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} onCancel={cancel} />)
          )}
        </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 gets a card background 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>
    );
  }
  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,
};

// One page for /jobs and /jobs/:id — master (list) + detail, resizable like /chat.
export const JobsPage = () => {
  const [layout, setLayout] = useState<LayoutNode>(JOBS_LAYOUT);
  return (
    <div className="h-full w-full">
      <WorkspaceLayout layout={layout} onLayoutChange={setLayout} components={PANEL_COMPONENTS} noHeader />
    </div>
  );
};
