import { Activity, AlertTriangle, CheckCircle, Clock, Key, Server, ShieldCheck, ShieldX, Wifi, WifiOff } from 'lucide-react';

import { useState } from 'react';

import { Head, Link, router } from '@inertiajs/react';

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { ConfirmDialog } from '@/Components/ui/confirm-dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { useAdminKeyboardShortcuts } from '@/hooks/useAdminKeyboardShortcuts';
import { useNavigationState } from '@/hooks/useNavigationState';
import AdminLayout from '@/Layouts/AdminLayout';
import { cn } from '@/lib/utils';

interface StuckJob {
  type: string;
  id: number;
  site_name: string | null;
  started_at: string | null;
  hours_stuck: number;
}

interface RecentFailure {
  uuid: string;
  connection: string;
  queue: string;
  exception: string;
  failed_at: string;
}

interface ByokHealth {
  total: number;
  valid: number;
  invalid: number;
  never_validated: number;
  rate_limited: number;
  quota_exceeded: number;
  consecutive_failures_3plus: number;
}

interface ConnectionHealthSide {
  total: number;
  unhealthy: number;
}

interface ConnectionHealth {
  gsc: ConnectionHealthSide;
  wp: ConnectionHealthSide;
}

interface QueueDepthEntry {
  queue: string;
  depth: number;
  oldest_job_minutes: number;
}

interface Props {
  active_jobs: {
    analysis_runs: number;
    ai_jobs: number;
    batch_jobs: number;
  };
  queue_health: {
    pending: number;
    failed_24h: number;
    failed_1h: number;
    oldest_pending_minutes: number | null;
    by_queue: QueueDepthEntry[];
  };
  stuck_jobs: StuckJob[];
  recent_failures: RecentFailure[];
  byok_health: ByokHealth;
  connection_health: ConnectionHealth;
}

function jobTypeSlug(type: string): string {
  return type === 'AnalysisRun' ? 'analysis_run' : 'ai_job';
}

export default function Index({ active_jobs, queue_health, stuck_jobs, recent_failures, byok_health, connection_health }: Props) {
  const totalActive = active_jobs.analysis_runs + active_jobs.ai_jobs + active_jobs.batch_jobs;
  const [cancellingJob, setCancellingJob] = useState<StuckJob | null>(null);
  const isNavigating = useNavigationState();
  useAdminKeyboardShortcuts({});

  const handleCancel = () => {
    if (!cancellingJob) return;
    router.post(
      route('admin.operations.jobs.cancel', {
        type: jobTypeSlug(cancellingJob.type),
        id: cancellingJob.id,
      }),
      {},
      {
        preserveScroll: true,
        onFinish: () => setCancellingJob(null),
      },
    );
  };

  const statCards: StatCard[] = [
    { title: 'Active Jobs', value: totalActive, icon: Activity },
    { title: 'Queue Pending', value: queue_health.pending, icon: Clock },
    {
      title: 'Failed (24h)',
      value: queue_health.failed_24h,
      icon: AlertTriangle,
      valueClassName: queue_health.failed_24h > 0 ? 'text-destructive' : '',
    },
    {
      title: 'Stuck Jobs',
      value: stuck_jobs.length,
      icon: Server,
      valueClassName: stuck_jobs.length > 0 ? 'text-destructive' : '',
    },
  ];

  return (
    <AdminLayout>
      <Head title="Operations" />
      <div className="container py-6 space-y-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>Operations</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <PageHeader
          title="Operations Dashboard"
          description="System health and job pipeline status"
        />

        <ChartErrorBoundary label="Unable to load operations data">
        <AdminStatsGrid stats={statCards} />

        <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Analysis Runs</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{active_jobs.analysis_runs}</p>
              <p className="text-xs text-muted-foreground">processing</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">AI Jobs</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{active_jobs.ai_jobs}</p>
              <p className="text-xs text-muted-foreground">processing</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Batch Jobs</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{active_jobs.batch_jobs}</p>
              <p className="text-xs text-muted-foreground">processing</p>
            </CardContent>
          </Card>
        </div>

        {queue_health.pending > 0 && (
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">Queue Depth</CardTitle>
                {queue_health.oldest_pending_minutes !== null && (
                  <span
                    className={cn(
                      'text-xs font-medium',
                      queue_health.oldest_pending_minutes >= 60
                        ? 'text-destructive'
                        : queue_health.oldest_pending_minutes >= 15
                          ? 'text-warning-high'
                          : queue_health.oldest_pending_minutes >= 5
                            ? 'text-warning'
                            : 'text-muted-foreground',
                    )}
                  >
                    Oldest job: {queue_health.oldest_pending_minutes}m ago
                  </span>
                )}
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              {queue_health.failed_1h > 0 && (
                <div className="flex items-center gap-2 text-sm">
                  <AlertTriangle className="h-4 w-4 shrink-0 text-destructive" />
                  <span className="font-medium text-destructive">
                    {queue_health.failed_1h} failed in last hour
                  </span>
                  {queue_health.failed_24h > queue_health.failed_1h && (
                    <span className="text-muted-foreground">
                      ({queue_health.failed_24h} in 24h)
                    </span>
                  )}
                </div>
              )}

              {queue_health.by_queue.length > 0 && (
                <div className="space-y-1.5">
                  {queue_health.by_queue.map((q) => (
                    <div
                      key={q.queue}
                      className="flex items-center justify-between rounded-md border px-3 py-2 text-sm"
                    >
                      <span className="font-mono text-xs">{q.queue}</span>
                      <div className="flex items-center gap-4">
                        <span
                          className={cn(
                            'font-bold tabular-nums',
                            q.depth > 50
                              ? 'text-destructive'
                              : q.depth > 10
                                ? 'text-warning'
                                : 'text-foreground',
                          )}
                        >
                          {q.depth}
                        </span>
                        <span className="w-20 text-right text-xs text-muted-foreground">
                          {q.oldest_job_minutes}m wait
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {queue_health.oldest_pending_minutes !== null &&
                queue_health.oldest_pending_minutes >= 15 && (
                  <div className="flex items-start gap-2 rounded-md border border-warning p-2 text-sm">
                    <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warning" />
                    <span className="text-warning">
                      {queue_health.oldest_pending_minutes >= 60
                        ? 'Jobs have been pending for over 1 hour — workers may be down or unavailable'
                        : 'Jobs have been pending for over 15 minutes — workers may be slow or backlogged'}
                    </span>
                  </div>
                )}
            </CardContent>
          </Card>
        )}

        {stuck_jobs.length > 0 && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-base font-semibold text-destructive">
                Stuck Jobs ({stuck_jobs.length})
              </h3>
              <Link
                href="/admin/system"
                className="text-sm text-muted-foreground hover:text-foreground hover:underline"
              >
                Manage failed jobs &rarr;
              </Link>
            </div>
            <AdminDataTable isEmpty={false} isNavigating={isNavigating}>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Type</TableHead>
                    <TableHead>ID</TableHead>
                    <TableHead>Site</TableHead>
                    <TableHead>Hours Stuck</TableHead>
                    <TableHead className="w-24" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stuck_jobs.map((job, idx) => (
                    <TableRow key={idx}>
                      <TableCell>
                        <Badge variant="destructive">{job.type}</Badge>
                      </TableCell>
                      <TableCell className="font-mono text-xs">{job.id}</TableCell>
                      <TableCell className="text-sm">{job.site_name ?? '—'}</TableCell>
                      <TableCell className="text-sm font-mono">{job.hours_stuck}h</TableCell>
                      <TableCell>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => setCancellingJob(job)}
                        >
                          Cancel
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </AdminDataTable>
          </div>
        )}

        {recent_failures.length > 0 && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="text-base font-semibold">
                Recent Failures ({recent_failures.length})
              </h3>
              <Link
                href="/admin/dlq"
                className="text-sm text-muted-foreground hover:text-foreground hover:underline"
              >
                Dead Letter Queue &rarr;
              </Link>
            </div>
            <AdminDataTable isEmpty={false} isNavigating={isNavigating}>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Queue</TableHead>
                    <TableHead>Error</TableHead>
                    <TableHead>Failed At</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {recent_failures.map((failure) => (
                    <TableRow key={failure.uuid}>
                      <TableCell className="text-sm">{failure.queue}</TableCell>
                      <TableCell className="max-w-100 truncate text-xs font-mono text-muted-foreground">
                        {failure.exception}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {failure.failed_at}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </AdminDataTable>
          </div>
        )}

        {byok_health.total > 0 && (
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">BYOK AI Key Health</CardTitle>
                <Link
                  href="/admin/ai-keys"
                  className="text-sm text-muted-foreground hover:text-foreground hover:underline"
                >
                  View all keys &rarr;
                </Link>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3 sm:grid-cols-3">
                <div className="flex items-center gap-3 rounded-md border p-3">
                  <ShieldCheck className="h-5 w-5 shrink-0 text-success" />
                  <div>
                    <p className="text-xs text-muted-foreground">Valid</p>
                    <p className="text-xl font-bold">{byok_health.valid}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3 rounded-md border p-3">
                  <ShieldX className="h-5 w-5 shrink-0 text-destructive" />
                  <div>
                    <p className="text-xs text-muted-foreground">Invalid / Errors</p>
                    <p className="text-xl font-bold">{byok_health.invalid}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3 rounded-md border p-3">
                  <Key className="h-5 w-5 shrink-0 text-muted-foreground" />
                  <div>
                    <p className="text-xs text-muted-foreground">Never Validated</p>
                    <p className="text-xl font-bold">{byok_health.never_validated}</p>
                  </div>
                </div>
              </div>
              {(byok_health.rate_limited > 0 || byok_health.quota_exceeded > 0 || byok_health.consecutive_failures_3plus > 0) && (
                <div className="mt-3 flex flex-wrap gap-2">
                  {byok_health.rate_limited > 0 && (
                    <Badge variant="outline" className="text-warning border-warning">
                      {byok_health.rate_limited} rate-limited
                    </Badge>
                  )}
                  {byok_health.quota_exceeded > 0 && (
                    <Badge variant="outline" className="text-warning-high border-warning-high">
                      {byok_health.quota_exceeded} quota exceeded
                    </Badge>
                  )}
                  {byok_health.consecutive_failures_3plus > 0 && (
                    <Badge variant="destructive">
                      {byok_health.consecutive_failures_3plus} with 3+ failures
                    </Badge>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {(connection_health.gsc.total > 0 || connection_health.wp.total > 0) && (
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">Connection Health</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3 sm:grid-cols-2">
                <div className="flex items-center justify-between rounded-md border p-3">
                  <div className="flex items-center gap-3">
                    {connection_health.gsc.unhealthy > 0 ? (
                      <WifiOff className="h-5 w-5 shrink-0 text-destructive" />
                    ) : (
                      <Wifi className="h-5 w-5 shrink-0 text-success" />
                    )}
                    <div>
                      <p className="text-xs text-muted-foreground">GSC Connections</p>
                      <p className="text-xl font-bold">{connection_health.gsc.total}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    {connection_health.gsc.unhealthy > 0 ? (
                      <span className="text-sm font-medium text-destructive">
                        {connection_health.gsc.unhealthy} unhealthy
                      </span>
                    ) : (
                      <span className="text-sm text-muted-foreground">All healthy</span>
                    )}
                    <div>
                      <Link
                        href="/admin/gsc-connections"
                        className="text-xs text-muted-foreground hover:text-foreground hover:underline"
                      >
                        View all &rarr;
                      </Link>
                    </div>
                  </div>
                </div>
                <div className="flex items-center justify-between rounded-md border p-3">
                  <div className="flex items-center gap-3">
                    {connection_health.wp.unhealthy > 0 ? (
                      <WifiOff className="h-5 w-5 shrink-0 text-destructive" />
                    ) : (
                      <Wifi className="h-5 w-5 shrink-0 text-success" />
                    )}
                    <div>
                      <p className="text-xs text-muted-foreground">WP Connections</p>
                      <p className="text-xl font-bold">{connection_health.wp.total}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    {connection_health.wp.unhealthy > 0 ? (
                      <span className="text-sm font-medium text-destructive">
                        {connection_health.wp.unhealthy} unhealthy
                      </span>
                    ) : (
                      <span className="text-sm text-muted-foreground">All healthy</span>
                    )}
                    <div>
                      <Link
                        href="/admin/wp-connections"
                        className="text-xs text-muted-foreground hover:text-foreground hover:underline"
                      >
                        View all &rarr;
                      </Link>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {totalActive === 0 &&
          queue_health.pending === 0 &&
          queue_health.failed_24h === 0 &&
          stuck_jobs.length === 0 &&
          recent_failures.length === 0 && (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <CheckCircle className="mb-3 h-10 w-10 text-success" />
                <p className="text-lg font-semibold">All systems operational</p>
                <p className="text-sm text-muted-foreground">
                  No active jobs, failures, or stuck processes.
                </p>
              </CardContent>
            </Card>
          )}
        </ChartErrorBoundary>
      </div>

      <ConfirmDialog
        open={cancellingJob !== null}
        onOpenChange={(open) => {
          if (!open) setCancellingJob(null);
        }}
        title="Cancel stuck job?"
        description={
          cancellingJob
            ? `This will mark ${cancellingJob.type} #${cancellingJob.id} as failed. The job has been stuck for ${cancellingJob.hours_stuck}h.`
            : ''
        }
        variant="destructive"
        confirmLabel="Cancel Job"
        onConfirm={handleCancel}
      />
    </AdminLayout>
  );
}
