import { toast } from 'sonner';

import { useCallback, useState } from 'react';

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

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 { EmptyState } from '@/Components/ui/empty-state';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime } from '@/lib/format';
import type { AdminSystemProps, FailedJob } from '@/types/admin';

export default function AdminSystem({ system }: AdminSystemProps) {
  const [failedJobs, setFailedJobs] = useState<FailedJob[]>([]);
  const [isExpanded, setIsExpanded] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [retrying, setRetrying] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);
  const [confirmingDelete, setConfirmingDelete] = useState<string | null>(null);
  const [flushCacheOpen, setFlushCacheOpen] = useState(false);

  const fetchFailedJobs = useCallback(() => {
    setIsLoading(true);
    fetch(route('admin.system.failed-jobs'), {
      headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
      credentials: 'same-origin',
    })
      .then((res) => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}`);
        }
        return res.json();
      })
      .then((data: FailedJob[]) => {
        setFailedJobs(data);
        setIsLoading(false);
      })
      .catch(() => {
        setFailedJobs([]);
        setIsLoading(false);
      });
  }, []);

  const toggleExpanded = () => {
    const next = !isExpanded;
    setIsExpanded(next);
    if (next) {
      fetchFailedJobs();
    }
  };

  const handleRetry = (uuid: string) => {
    setRetrying(uuid);
    router.post(
      route('admin.system.failed-jobs.retry', { uuid }),
      {},
      {
        preserveScroll: true,
        onSuccess: () => toast.success('Job queued for retry.'),
        onFinish: () => {
          setRetrying(null);
          fetchFailedJobs();
        },
      },
    );
  };

  const handleDelete = (uuid: string) => {
    setDeleting(uuid);
    router.delete(route('admin.system.failed-jobs.delete', { uuid }), {
      preserveScroll: true,
      onSuccess: () => toast.success('Failed job deleted.'),
      onFinish: () => {
        setDeleting(null);
        setConfirmingDelete(null);
        fetchFailedJobs();
      },
    });
  };

  const failedCount = system.queue.failed_jobs;

  return (
    <AdminLayout>
      <Head title="Admin - System Info" />

      <div className="container py-6 space-y-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>System Info</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <PageHeader title="System Info" subtitle="Runtime and dependency information" />
        <div className="grid gap-6 md:grid-cols-2">
          {/* Runtime */}
          <Card>
            <CardHeader>
              <CardTitle>Runtime</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">PHP</span>
                <span className="text-sm font-mono">{system.php_version}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Laravel</span>
                <span className="text-sm font-mono">{system.laravel_version}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Node.js</span>
                <span className="text-sm font-mono">
                  {system.node_version ?? (
                    <span className="text-muted-foreground">Not available</span>
                  )}
                </span>
              </div>
            </CardContent>
          </Card>

          {/* Server */}
          <Card>
            <CardHeader>
              <CardTitle>Server</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">OS</span>
                <span className="text-sm font-mono">{system.server.os}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Server Software</span>
                <span className="text-sm font-mono">{system.server.server_software}</span>
              </div>
            </CardContent>
          </Card>

          {/* Database */}
          <Card>
            <CardHeader>
              <CardTitle>Database</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Driver</span>
                <span className="text-sm font-mono">{system.database.driver}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Version</span>
                <span className="text-sm font-mono">
                  {system.database.version ?? (
                    <span className="text-muted-foreground">Unknown</span>
                  )}
                </span>
              </div>
            </CardContent>
          </Card>

          {/* Queue */}
          <Card>
            <CardHeader>
              <CardTitle>Queue</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Driver</span>
                <span className="text-sm font-mono">{system.queue.driver}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-muted-foreground">Pending Jobs</span>
                <span className="text-sm">
                  {system.queue.pending_jobs !== null ? system.queue.pending_jobs : 'N/A'}
                </span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-muted-foreground">Failed Jobs</span>
                <span className="text-sm">
                  {failedCount !== null ? (
                    failedCount > 0 ? (
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-auto p-0"
                        onClick={toggleExpanded}
                        aria-label={`View ${failedCount} failed jobs`}
                      >
                        <Badge variant="destructive">{failedCount}</Badge>
                      </Button>
                    ) : (
                      failedCount
                    )
                  ) : (
                    'N/A'
                  )}
                </span>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Failed Jobs Table */}
        {isExpanded && (
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>Failed Jobs</CardTitle>
              <Button
                variant="outline"
                size="sm"
                onClick={fetchFailedJobs}
                disabled={isLoading}
                aria-label="Refresh failed jobs list"
              >
                {isLoading ? 'Loading...' : 'Refresh'}
              </Button>
            </CardHeader>
            <CardContent>
              {isLoading && failedJobs.length === 0 ? (
                <div className="space-y-3 py-4">
                  {Array.from({ length: 3 }).map((_, i) => (
                    <div key={i} className="flex items-center gap-4">
                      <Skeleton className="h-4 w-40" />
                      <Skeleton className="h-5 w-16 rounded-full" />
                      <Skeleton className="h-4 w-60" />
                      <Skeleton className="h-4 w-20" />
                      <Skeleton className="h-8 w-24 ml-auto" />
                    </div>
                  ))}
                </div>
              ) : failedJobs.length === 0 ? (
                <EmptyState
                  title="No failed jobs yet"
                  description="All queue jobs are healthy."
                  size="sm"
                />
              ) : (
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Job</TableHead>
                        <TableHead>Queue</TableHead>
                        <TableHead className="max-w-xs">Exception</TableHead>
                        <TableHead>Failed At</TableHead>
                        <TableHead className="text-right">Actions</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {failedJobs.map((job) => (
                        <TableRow key={job.uuid}>
                          <TableCell className="font-mono text-xs whitespace-nowrap">
                            {job.job_name}
                          </TableCell>
                          <TableCell>
                            <Badge variant="outline">{job.queue}</Badge>
                          </TableCell>
                          <TableCell
                            className="max-w-xs truncate text-xs text-muted-foreground"
                            title={job.exception}
                          >
                            {job.exception}
                          </TableCell>
                          <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                            {formatRelativeTime(job.failed_at)}
                          </TableCell>
                          <TableCell className="text-right space-x-2">
                            <Button
                              variant="outline"
                              size="sm"
                              disabled={retrying === job.uuid}
                              onClick={() => handleRetry(job.uuid)}
                              aria-label={`Retry ${job.job_name}`}
                            >
                              {retrying === job.uuid ? 'Retrying...' : 'Retry'}
                            </Button>
                            <Button
                              variant="destructive"
                              size="sm"
                              disabled={deleting === job.uuid}
                              onClick={() => setConfirmingDelete(job.uuid)}
                              aria-label={`Delete ${job.job_name}`}
                            >
                              {deleting === job.uuid ? 'Deleting...' : 'Delete'}
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* Cache Management */}
        <Card>
          <CardHeader>
            <CardTitle>Cache Management</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm">Admin Cache</p>
                <p className="text-xs text-muted-foreground">
                  Clears all cached admin metrics and dashboard data. Data will be reloaded from the database on the next page view.
                </p>
              </div>
              <Button variant="outline" onClick={() => setFlushCacheOpen(true)}>
                Flush Admin Cache
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Packages */}
        <Card>
          <CardHeader>
            <CardTitle>Key Packages</CardTitle>
          </CardHeader>
          <CardContent>
            {system.packages.length === 0 ? (
              <EmptyState
                title="Could not read composer.lock"
                description="Package version information is not available."
                size="sm"
              />
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Package</TableHead>
                      <TableHead>Version</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {system.packages.map((pkg) => (
                      <TableRow key={pkg.name}>
                        <TableCell className="font-medium">{pkg.name}</TableCell>
                        <TableCell className="font-mono text-sm">{pkg.version}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      <ConfirmDialog
        open={confirmingDelete !== null}
        onOpenChange={(open) => {
          if (!open) setConfirmingDelete(null);
        }}
        title="Delete failed job"
        description="Delete this failed job? This cannot be undone."
        variant="destructive"
        confirmLabel="Delete"
        onConfirm={() => {
          if (confirmingDelete) handleDelete(confirmingDelete);
        }}
      />

      <ConfirmDialog
        open={flushCacheOpen}
        onOpenChange={setFlushCacheOpen}
        title="Flush Admin Cache?"
        description="This clears all cached admin metrics and dashboard data. Data will be reloaded from the database on the next page view."
        confirmLabel="Flush Cache"
        onConfirm={() => {
          router.post(route('admin.system.flush-cache'), {}, {
            preserveScroll: true,
            onFinish: () => setFlushCacheOpen(false),
          });
        }}
      />
    </AdminLayout>
  );
}
