import { Trash2 } from 'lucide-react';

import { useState } from 'react';

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

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, 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';
import type { PageProps } from '@/types';

interface CacheGroup {
  name: string;
  prefix: string;
  description: string;
}

interface AdminCacheKey {
  key: string;
  cached: boolean;
}

interface Props {
  groups: CacheGroup[];
  admin_keys: AdminCacheKey[];
}

export default function CacheIndex({ groups, admin_keys }: Props) {
  const { auth } = usePage<PageProps>().props;
  const isNavigating = useNavigationState();
  const [flushGroupConfirm, setFlushGroupConfirm] = useState<string | null>(null);
  const [flushAllConfirm, setFlushAllConfirm] = useState(false);

  useAdminKeyboardShortcuts({});

  const canMutate = auth.user?.admin_role != null && auth.user.admin_role !== 'viewer';
  const isSuperAdmin = auth.user?.admin_role === 'super_admin';
  const cachedCount = admin_keys.filter((k) => k.cached).length;

  return (
    <AdminLayout>
      <Head title="Cache Management" />
      <div className={cn('container py-6 space-y-6', isNavigating && 'opacity-50 pointer-events-none')}>
        <PageHeader title="Cache Management" description="View and manage application caches" />

        <div className="grid gap-4 md:grid-cols-2">
          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium">Cache Groups</CardTitle>
              <CardDescription>Flush caches by functional group</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {groups.map((group) => (
                <div
                  key={group.name}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div>
                    <p className="text-sm font-medium capitalize">{group.name}</p>
                    <p className="text-xs text-muted-foreground">{group.description}</p>
                  </div>
                  {canMutate && (
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => setFlushGroupConfirm(group.name)}
                    >
                      <Trash2 className="h-3.5 w-3.5 mr-1" />
                      Flush
                    </Button>
                  )}
                </div>
              ))}
              {isSuperAdmin && (
                <Button
                  variant="destructive"
                  size="sm"
                  className="w-full mt-2"
                  onClick={() => setFlushAllConfirm(true)}
                >
                  Flush All Admin Caches
                </Button>
              )}
            </CardContent>
          </Card>

          <div className="flex flex-col gap-3">
            <div>
              <p className="text-sm font-medium">
                Admin Cache Keys ({cachedCount}/{admin_keys.length} populated)
              </p>
              <p className="text-xs text-muted-foreground">Known admin cache key status</p>
            </div>
            <div className="max-h-[400px] overflow-y-auto">
              <AdminDataTable
                isEmpty={admin_keys.length === 0}
                isNavigating={isNavigating}
                emptyTitle="No cache keys"
                emptyDescription="No admin cache keys are currently tracked."
              >
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Key</TableHead>
                      <TableHead className="w-20">Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {admin_keys.map((item) => (
                      <TableRow key={item.key}>
                        <TableCell className="font-mono text-xs">{item.key}</TableCell>
                        <TableCell>
                          <Badge variant={item.cached ? 'success' : 'outline'}>
                            {item.cached ? 'Cached' : 'Empty'}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </AdminDataTable>
            </div>
          </div>
        </div>
      </div>

      <ConfirmDialog
        open={flushGroupConfirm !== null}
        onOpenChange={() => setFlushGroupConfirm(null)}
        title={`Flush "${flushGroupConfirm}" cache?`}
        description="This will clear all cached data in this group. It will be rebuilt on next access."
        confirmLabel="Flush"
        onConfirm={() => {
          if (flushGroupConfirm) {
            router.post(route('admin.cache.flush'), { group: flushGroupConfirm });
            setFlushGroupConfirm(null);
          }
        }}
      />

      <ConfirmDialog
        open={flushAllConfirm}
        onOpenChange={setFlushAllConfirm}
        title="Flush all admin caches?"
        description="This will clear all admin panel caches. Dashboard data will reload from the database on next access."
        confirmLabel="Flush All"
        variant="destructive"
        onConfirm={() => {
          router.post(route('admin.cache.flush-all'));
          setFlushAllConfirm(false);
        }}
      />
    </AdminLayout>
  );
}
