'use client';

import { useCallback, useEffect, useState } from 'react';
import { BadgeCheck, RefreshCw, Send, TimerReset } from 'lucide-react';
import { createProxyFetch } from '@/lib/proxy-fetch';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';

type AgentSession = {
  sessionId: string;
  productId: string;
  userId: string;
  status: string;
  startedAt: string;
  updatedAt: string;
  resumable: boolean;
  dispatchContext?: {
    originSurface: string;
    dispatchMode: string;
  } | null;
};

type AgentRun = {
  runId: string;
  sessionId: string;
  productId: string;
  status: string;
  startedAt: string;
  completedAt?: string | null;
  correlationId?: string | null;
};

type AgentCheckpoint = {
  checkpointId: string;
  sessionId: string;
  runId?: string | null;
  productId: string;
  userId: string;
  createdAt: string;
  statusAtCapture: string;
  currentTaskId?: string | null;
  checkpointArtifactId?: string | null;
  artifactRefs: string[];
  memoryRefs: string[];
  approvalRefs: string[];
  resumeToken?: string | null;
  stateSummary: {
    title: string;
    summary: string;
    lastActionAt?: string | null;
  };
};

type AgentCheckpointDetail = {
  checkpoint: AgentCheckpoint;
  detail: {
    goal: string;
    folder?: string | null;
    model?: string | null;
    createdAt: string;
    updatedAt: string;
    completedToolCalls: number;
    completed: boolean;
    cancelled: boolean;
    error?: string | null;
    eventId?: string | null;
    correlationId?: string | null;
    source: {
      observationKind: string;
      projectionKind: string;
    };
    observedRefs: {
      checkpointArtifactId?: string | null;
      artifactRefs: string[];
      memoryRefs: string[];
      approvalRefs: string[];
    };
  };
};

const apiFetch = createProxyFetch('/api/agent-runtime');

function formatDate(iso: string | null | undefined) {
  if (!iso) return '—';
  return new Date(iso).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

export default function AgentRuntimePage() {
  const [sessions, setSessions] = useState<AgentSession[]>([]);
  const [runs, setRuns] = useState<AgentRun[]>([]);
  const [checkpoints, setCheckpoints] = useState<AgentCheckpoint[]>([]);
  const [selectedCheckpointId, setSelectedCheckpointId] = useState<string | null>(null);
  const [checkpointDetail, setCheckpointDetail] = useState<AgentCheckpointDetail | null>(null);
  const [checkpointLoading, setCheckpointLoading] = useState(false);
  const [loading, setLoading] = useState(true);
  const [userId, setUserId] = useState('');
  const [limit, setLimit] = useState('20');
  const [dispatchPayload, setDispatchPayload] = useState(
    JSON.stringify(
      {
        dispatchId: 'dispatch_example',
        targetProductId: 'lysnrai',
        targetExecutor: 'generic-agent',
        userId: 'user_1',
        title: 'Summarize the latest transcript',
        intent: 'Prepare a note and memory candidate.',
        artifactRefs: ['art_transcript_1'],
        memoryRefs: [],
        dispatchContext: {
          originSurface: 'web',
          originProductId: 'lysnrai',
          dispatchMode: 'interactive',
          initiatedAt: '2026-04-04T08:00:00.000Z',
        },
      },
      null,
      2
    )
  );
  const [dispatchResult, setDispatchResult] = useState<string>('');

  const loadData = useCallback(async () => {
    setLoading(true);
    const sessionParams = new URLSearchParams({ section: 'sessions' });
    if (userId.trim()) sessionParams.set('userId', userId.trim());

    const runParams = new URLSearchParams({ section: 'runs', limit });

    const checkpointParams = new URLSearchParams({
      section: 'checkpoints',
      productId: 'clawcowork',
      limit,
    });

    const [sessionData, runData, checkpointData] = await Promise.all([
      apiFetch(`?${sessionParams.toString()}`),
      apiFetch(`?${runParams.toString()}`),
      apiFetch(`?${checkpointParams.toString()}`),
    ]);

    setSessions(Array.isArray(sessionData?.sessions) ? sessionData.sessions : []);
    setRuns(Array.isArray(runData?.runs) ? runData.runs : []);
    const nextCheckpoints = Array.isArray(checkpointData?.checkpoints)
      ? checkpointData.checkpoints
      : [];
    setCheckpoints(nextCheckpoints);
    setSelectedCheckpointId(current =>
      nextCheckpoints.some((checkpoint: AgentCheckpoint) => checkpoint.checkpointId === current)
        ? current
        : (nextCheckpoints[0]?.checkpointId ?? null)
    );
    setLoading(false);
  }, [limit, userId]);

  const loadCheckpointDetail = useCallback(async (checkpointId: string | null) => {
    if (!checkpointId) {
      setCheckpointDetail(null);
      return;
    }

    setCheckpointLoading(true);
    const detail = await apiFetch(
      `?section=checkpoint-detail&productId=clawcowork&checkpointId=${encodeURIComponent(checkpointId)}`
    );
    setCheckpointDetail(detail?.checkpoint ? detail : null);
    setCheckpointLoading(false);
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  useEffect(() => {
    void loadCheckpointDetail(selectedCheckpointId);
  }, [loadCheckpointDetail, selectedCheckpointId]);

  async function validateDispatch() {
    try {
      const parsed = JSON.parse(dispatchPayload);
      const result = await apiFetch('', {
        method: 'POST',
        body: JSON.stringify(parsed),
      });
      setDispatchResult(JSON.stringify(result, null, 2));
    } catch (error) {
      setDispatchResult(
        JSON.stringify(
          {
            error: error instanceof Error ? error.message : 'Invalid JSON payload',
          },
          null,
          2
        )
      );
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Agent Runtime</h1>
          <p className="text-sm text-muted-foreground">
            Inspect shared runtime projections and validate dispatch payloads
          </p>
        </div>
        <Button variant="outline" onClick={() => void loadData()}>
          <RefreshCw className="mr-2 h-4 w-4" /> Refresh
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Sessions</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{sessions.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Runs</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{runs.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Active Runs</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {runs.filter(run => run.status === 'running').length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Resumable Sessions
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {sessions.filter(session => session.resumable).length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Cowork Checkpoints
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{checkpoints.length}</div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-3 md:grid-cols-3">
        <Input
          placeholder="Filter sessions by user ID"
          value={userId}
          onChange={event => setUserId(event.target.value)}
        />
        <Input
          placeholder="Run limit"
          value={limit}
          onChange={event => setLimit(event.target.value)}
        />
      </div>

      <Tabs defaultValue="sessions" className="space-y-4">
        <TabsList>
          <TabsTrigger value="sessions">Sessions</TabsTrigger>
          <TabsTrigger value="runs">Runs</TabsTrigger>
          <TabsTrigger value="checkpoints">Cowork Checkpoints</TabsTrigger>
          <TabsTrigger value="dispatch">Dispatch Validation</TabsTrigger>
        </TabsList>

        <TabsContent value="sessions">
          <Card>
            <CardContent className="space-y-3 p-4">
              {loading ? (
                <div className="text-sm text-muted-foreground">Loading sessions...</div>
              ) : sessions.length === 0 ? (
                <div className="text-sm text-muted-foreground">No runtime sessions found.</div>
              ) : (
                sessions.map(session => (
                  <div key={session.sessionId} className="rounded-lg border p-3">
                    <div className="mb-2 flex flex-wrap items-center gap-2">
                      <div className="font-medium">{session.sessionId}</div>
                      <Badge variant="outline">{session.status}</Badge>
                      <Badge variant="outline">{session.productId}</Badge>
                      {session.resumable && (
                        <Badge className="bg-emerald-50 text-emerald-700 border-0">resumable</Badge>
                      )}
                    </div>
                    <div className="grid gap-2 text-sm md:grid-cols-4">
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          User
                        </div>
                        <div className="font-mono text-xs">{session.userId}</div>
                      </div>
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Started
                        </div>
                        <div>{formatDate(session.startedAt)}</div>
                      </div>
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Updated
                        </div>
                        <div>{formatDate(session.updatedAt)}</div>
                      </div>
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Dispatch
                        </div>
                        <div className="text-xs">
                          {session.dispatchContext
                            ? `${session.dispatchContext.originSurface} · ${session.dispatchContext.dispatchMode}`
                            : '—'}
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="runs">
          <Card>
            <CardContent className="space-y-3 p-4">
              {loading ? (
                <div className="text-sm text-muted-foreground">Loading runs...</div>
              ) : runs.length === 0 ? (
                <div className="text-sm text-muted-foreground">No runtime runs found.</div>
              ) : (
                runs.map(run => (
                  <div key={run.runId} className="rounded-lg border p-3">
                    <div className="mb-2 flex flex-wrap items-center gap-2">
                      <div className="font-medium">{run.runId}</div>
                      <Badge variant="outline">{run.status}</Badge>
                      <Badge variant="outline">{run.productId}</Badge>
                    </div>
                    <div className="grid gap-2 text-sm md:grid-cols-4">
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Session
                        </div>
                        <div className="font-mono text-xs">{run.sessionId}</div>
                      </div>
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Started
                        </div>
                        <div>{formatDate(run.startedAt)}</div>
                      </div>
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Completed
                        </div>
                        <div>{formatDate(run.completedAt)}</div>
                      </div>
                      <div>
                        <div className="text-xs uppercase tracking-wide text-muted-foreground">
                          Correlation
                        </div>
                        <div className="font-mono text-xs">{run.correlationId || '—'}</div>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="checkpoints">
          <div className="grid gap-4 xl:grid-cols-[1.2fr,0.8fr]">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Checkpoint Summaries</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {loading ? (
                  <div className="text-sm text-muted-foreground">Loading checkpoints...</div>
                ) : checkpoints.length === 0 ? (
                  <div className="text-sm text-muted-foreground">
                    No Cowork checkpoints are currently available.
                  </div>
                ) : (
                  checkpoints.map(checkpoint => (
                    <button
                      key={checkpoint.checkpointId}
                      type="button"
                      onClick={() => setSelectedCheckpointId(checkpoint.checkpointId)}
                      className={`w-full rounded-lg border p-3 text-left transition ${
                        selectedCheckpointId === checkpoint.checkpointId
                          ? 'border-emerald-500 bg-emerald-50/60'
                          : 'hover:bg-muted/20'
                      }`}
                    >
                      <div className="mb-2 flex flex-wrap items-center gap-2">
                        <div className="font-medium">{checkpoint.stateSummary.title}</div>
                        <Badge variant="outline">{checkpoint.statusAtCapture}</Badge>
                        <Badge variant="outline">clawcowork</Badge>
                      </div>
                      <div className="mb-3 text-sm text-muted-foreground">
                        {checkpoint.stateSummary.summary}
                      </div>
                      <div className="grid gap-2 text-sm md:grid-cols-3">
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Checkpoint
                          </div>
                          <div className="font-mono text-xs">{checkpoint.checkpointId}</div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Run
                          </div>
                          <div className="font-mono text-xs">{checkpoint.runId || '—'}</div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Last Action
                          </div>
                          <div>
                            {formatDate(
                              checkpoint.stateSummary.lastActionAt || checkpoint.createdAt
                            )}
                          </div>
                        </div>
                      </div>
                    </button>
                  ))
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Checkpoint Drill-In</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {checkpointLoading ? (
                  <div className="text-sm text-muted-foreground">Loading checkpoint detail...</div>
                ) : !checkpointDetail ? (
                  <div className="text-sm text-muted-foreground">
                    Select a checkpoint to inspect direct Cowork observations and projected runtime
                    summary fields.
                  </div>
                ) : (
                  <>
                    <div className="rounded-lg border bg-muted/20 p-3">
                      <div className="mb-2 flex flex-wrap items-center gap-2">
                        <Badge className="bg-sky-50 text-sky-700 border-0">
                          direct observation
                        </Badge>
                        <Badge variant="outline">
                          {checkpointDetail.detail.source.observationKind}
                        </Badge>
                      </div>
                      <div className="grid gap-3 text-sm md:grid-cols-2">
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Goal
                          </div>
                          <div>{checkpointDetail.detail.goal}</div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Model
                          </div>
                          <div>{checkpointDetail.detail.model || '—'}</div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Folder
                          </div>
                          <div className="font-mono text-xs">
                            {checkpointDetail.detail.folder || '—'}
                          </div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Tool Calls
                          </div>
                          <div>{checkpointDetail.detail.completedToolCalls}</div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Event ID
                          </div>
                          <div className="font-mono text-xs">
                            {checkpointDetail.detail.eventId || '—'}
                          </div>
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Correlation
                          </div>
                          <div className="font-mono text-xs">
                            {checkpointDetail.detail.correlationId || '—'}
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="rounded-lg border bg-muted/20 p-3">
                      <div className="mb-2 flex flex-wrap items-center gap-2">
                        <Badge className="bg-emerald-50 text-emerald-700 border-0">
                          projected summary
                        </Badge>
                        <Badge variant="outline">
                          {checkpointDetail.detail.source.projectionKind}
                        </Badge>
                      </div>
                      <div className="space-y-2 text-sm">
                        <div>
                          <div className="text-xs uppercase tracking-wide text-muted-foreground">
                            Summary
                          </div>
                          <div>{checkpointDetail.checkpoint.stateSummary.summary}</div>
                        </div>
                        <div className="grid gap-3 md:grid-cols-2">
                          <div>
                            <div className="text-xs uppercase tracking-wide text-muted-foreground">
                              Resume Token
                            </div>
                            <div className="font-mono text-xs">
                              {checkpointDetail.checkpoint.resumeToken || '—'}
                            </div>
                          </div>
                          <div>
                            <div className="text-xs uppercase tracking-wide text-muted-foreground">
                              Checkpoint Artifact
                            </div>
                            <div className="font-mono text-xs">
                              {checkpointDetail.detail.observedRefs.checkpointArtifactId || '—'}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="grid gap-3 md:grid-cols-3">
                      <div className="rounded-lg border p-3">
                        <div className="mb-2 text-xs uppercase tracking-wide text-muted-foreground">
                          Artifact Refs
                        </div>
                        <div className="space-y-2 text-xs">
                          {checkpointDetail.detail.observedRefs.artifactRefs.length > 0
                            ? checkpointDetail.detail.observedRefs.artifactRefs.map(ref => (
                                <div key={ref} className="font-mono">
                                  {ref}
                                </div>
                              ))
                            : '—'}
                        </div>
                      </div>
                      <div className="rounded-lg border p-3">
                        <div className="mb-2 text-xs uppercase tracking-wide text-muted-foreground">
                          Memory Refs
                        </div>
                        <div className="space-y-2 text-xs">
                          {checkpointDetail.detail.observedRefs.memoryRefs.length > 0
                            ? checkpointDetail.detail.observedRefs.memoryRefs.map(ref => (
                                <div key={ref} className="font-mono">
                                  {ref}
                                </div>
                              ))
                            : '—'}
                        </div>
                      </div>
                      <div className="rounded-lg border p-3">
                        <div className="mb-2 text-xs uppercase tracking-wide text-muted-foreground">
                          Approval Refs
                        </div>
                        <div className="space-y-2 text-xs">
                          {checkpointDetail.detail.observedRefs.approvalRefs.length > 0
                            ? checkpointDetail.detail.observedRefs.approvalRefs.map(ref => (
                                <div key={ref} className="font-mono">
                                  {ref}
                                </div>
                              ))
                            : '—'}
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="dispatch">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <Send className="h-4 w-4" />
                Dispatch Validation
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <Textarea
                value={dispatchPayload}
                onChange={event => setDispatchPayload(event.target.value)}
                className="min-h-[240px] font-mono text-xs"
              />
              <Button onClick={() => void validateDispatch()}>
                <BadgeCheck className="mr-2 h-4 w-4" />
                Validate Payload
              </Button>
              <div className="rounded-lg border bg-muted/20 p-3">
                <div className="mb-2 flex items-center gap-2 text-sm font-medium">
                  <TimerReset className="h-4 w-4" />
                  Validation Result
                </div>
                <pre className="overflow-x-auto text-xs">
                  {dispatchResult || 'Run validation to inspect the result.'}
                </pre>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
