import { useState, useMemo, ReactNode } from 'react';
import { Head, Link } from '@inertiajs/react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import AdminLayout from '@/layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import { Bot, Wrench, FileText, TrendingUp, Activity, ExternalLink, Search } from 'lucide-react';
import { format } from 'date-fns';
import { toast } from 'sonner';
import { useAuth } from '@/hooks/useAuth';

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const SERVICE_META: Record<string, { label: string; icon: React.ElementType; description: string; launchHref?: string }> = {
  ai_risk_assessor: {
    label: 'AI Risk Assessor',
    icon: Bot,
    description: 'Live camera hazard detection & RAMS generation.',
    launchHref: '/admin/risk-assessor',
  },
  ar_engineer_support: {
    label: 'AR Engineer Support',
    icon: Wrench,
    description: 'AI technical guidance for field engineers.',
    launchHref: '/admin/ar-assist',
  },
  compliance_docs: {
    label: 'Compliance Documents',
    icon: FileText,
    description: 'AI-generated compliance documentation.',
    launchHref: '/admin/compliance-docs',
  },
  skills_gap_analysis: {
    label: 'Skills Gap Analysis',
    icon: TrendingUp,
    description: 'Workforce skills gap identification.',
    launchHref: '/admin/skills-gap',
  },
};

const SERVICE_TYPES = Object.keys(SERVICE_META);

const ServicesPage = () => {
  const { isSysLevel } = useAuth();
  const isSysAdmin = isSysLevel();
  const qc = useQueryClient();
  const [search, setSearch] = useState('');

  const { data: companies } = useQuery({
    queryKey: ['all-training-companies-min'],
    queryFn: async () => {
      const res = await fetch('/api/admin/training-companies?fields=min');
      if (!res.ok) return [];
      return res.json();
    },
  });

  const { data: allServices } = useQuery({
    queryKey: ['all-company-services'],
    queryFn: async () => {
      const res = await fetch('/api/admin/company-services');
      if (!res.ok) return [];
      return res.json();
    },
  });

  const { data: usageLogs } = useQuery({
    queryKey: ['all-usage-logs'],
    queryFn: async () => {
      const res = await fetch('/api/admin/service-usage-log?limit=50');
      if (!res.ok) return [];
      return res.json();
    },
  });

  const toggleService = useMutation({
    mutationFn: async ({ companyId, serviceType, isActive }: { companyId: string; serviceType: string; isActive: boolean }) => {
      if (isActive) {
        const res = await fetch('/api/admin/company-services', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
          body: JSON.stringify({ company_id: companyId, service_type: serviceType, status: 'active' }),
        });
        if (!res.ok) throw new Error('Failed to activate service');
      } else {
        const res = await fetch(`/api/admin/company-services?company_id=${encodeURIComponent(companyId)}&service_type=${encodeURIComponent(serviceType)}`, {
          method: 'DELETE',
          headers: { 'X-CSRF-TOKEN': csrfToken() },
        });
        if (!res.ok) throw new Error('Failed to deactivate service');
      }
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['all-company-services'] });
      toast.success('Service updated');
    },
    onError: (e: any) => toast.error(e?.message || 'Failed to update service'),
  });

  // Aggregate stats
  const serviceTypeCounts: Record<string, number> = {};
  (allServices as any[] | undefined)?.forEach((s) => {
    if (s.status === 'active') {
      serviceTypeCounts[s.service_type] = (serviceTypeCounts[s.service_type] || 0) + 1;
    }
  });

  const usageByType: Record<string, number> = {};
  (usageLogs as any[] | undefined)?.forEach((l) => {
    usageByType[l.service_type] = (usageByType[l.service_type] || 0) + 1;
  });

  const isEnabled = (companyId: string, type: string) =>
    !!(allServices as any[] | undefined)?.some((s) => s.company_id === companyId && s.service_type === type && s.status === 'active');

  const filteredCompanies = useMemo(() => {
    const q = search.trim().toLowerCase();
    const list = (companies as any[] | undefined) || [];
    if (!q) return list;
    return list.filter((c) => c.name.toLowerCase().includes(q));
  }, [companies, search]);

  return (
    <>
      <Head title="Services Management" />
      <div>
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-foreground">Services Management</h1>
            <p className="text-sm text-muted-foreground mt-1">
              Activate AI & compliance services per company. Launch tools directly from this page.
            </p>
          </div>
        </div>

        {/* Overview cards with quick-launch */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          {Object.entries(SERVICE_META).map(([type, meta]) => {
            const Icon = meta.icon;
            const active = serviceTypeCounts[type] || 0;
            const usage = usageByType[type] || 0;
            return (
              <Card key={type}>
                <CardContent className="py-4">
                  <div className="flex items-center gap-3 mb-2">
                    <Icon className="h-5 w-5 text-primary" />
                    <p className="font-medium text-sm text-foreground">{meta.label}</p>
                  </div>
                  <p className="text-xs text-muted-foreground mb-3 line-clamp-2">{meta.description}</p>
                  <div className="flex items-center gap-4 mb-3">
                    <div>
                      <p className="text-2xl font-bold text-foreground">{active}</p>
                      <p className="text-xs text-muted-foreground">Active</p>
                    </div>
                    <div>
                      <p className="text-2xl font-bold text-foreground">{usage}</p>
                      <p className="text-xs text-muted-foreground">Recent uses</p>
                    </div>
                  </div>
                  {meta.launchHref && (
                    <Button asChild variant="outline" size="sm" className="w-full h-8 text-xs">
                      <Link href={meta.launchHref}>
                        <ExternalLink className="h-3 w-3 mr-1.5" /> Open tool
                      </Link>
                    </Button>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>

        {/* Per-company entitlements grid (sys_admin only) */}
        {isSysAdmin && (
          <Card className="mb-6">
            <CardHeader className="flex flex-row items-center justify-between gap-4">
              <CardTitle>Company Entitlements</CardTitle>
              <div className="relative w-64">
                <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                <Input
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder="Search companies…"
                  className="pl-8 h-8 text-sm"
                />
              </div>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Company</TableHead>
                    {SERVICE_TYPES.map((t) => (
                      <TableHead key={t} className="text-center">{SERVICE_META[t].label}</TableHead>
                    ))}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredCompanies.map((c: any) => (
                    <TableRow key={c.id}>
                      <TableCell className="font-medium text-sm">
                        <Link href={`/admin/companies/${c.id}`} className="hover:underline">
                          {c.name}
                        </Link>
                        <p className="text-[11px] text-muted-foreground capitalize">{c.company_type.replace(/_/g, ' ')}</p>
                      </TableCell>
                      {SERVICE_TYPES.map((t) => (
                        <TableCell key={t} className="text-center">
                          <Switch
                            checked={isEnabled(c.id, t)}
                            disabled={toggleService.isPending}
                            onCheckedChange={(checked) =>
                              toggleService.mutate({ companyId: c.id, serviceType: t, isActive: checked })
                            }
                          />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))}
                  {!filteredCompanies.length && (
                    <TableRow>
                      <TableCell colSpan={SERVICE_TYPES.length + 1} className="text-center text-muted-foreground py-8">
                        No companies found.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )}

        {/* Active subscriptions */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Active Subscriptions</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Company</TableHead>
                  <TableHead>Service</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Activated</TableHead>
                  <TableHead>Expires</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(allServices as any[] | undefined)?.map((s: any) => {
                  const meta = SERVICE_META[s.service_type];
                  return (
                    <TableRow key={s.id}>
                      <TableCell className="font-medium text-sm">{(s.company as any)?.name || '—'}</TableCell>
                      <TableCell className="text-sm">{meta?.label || s.service_type}</TableCell>
                      <TableCell>
                        <Badge variant={s.status === 'active' ? 'default' : s.status === 'trial' ? 'secondary' : 'destructive'} className="capitalize">
                          {s.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm">{format(new Date(s.activated_at), 'dd MMM yyyy')}</TableCell>
                      <TableCell className="text-sm">{s.expires_at ? format(new Date(s.expires_at), 'dd MMM yyyy') : 'No expiry'}</TableCell>
                    </TableRow>
                  );
                })}
                {!(allServices as any[] | undefined)?.length && (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center text-muted-foreground py-8">No services activated yet.</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Recent usage */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Activity className="h-5 w-5" /> Recent Usage
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Company</TableHead>
                  <TableHead>Service</TableHead>
                  <TableHead>Action</TableHead>
                  <TableHead>Date</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(usageLogs as any[] | undefined)?.map((log: any) => (
                  <TableRow key={log.id}>
                    <TableCell className="text-sm">{(log.company as any)?.name || '—'}</TableCell>
                    <TableCell className="capitalize text-sm">{log.service_type.replace(/_/g, ' ')}</TableCell>
                    <TableCell className="capitalize text-sm">{log.action.replace(/_/g, ' ')}</TableCell>
                    <TableCell className="text-sm">{format(new Date(log.created_at), 'dd MMM yyyy HH:mm')}</TableCell>
                  </TableRow>
                ))}
                {!(usageLogs as any[] | undefined)?.length && (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center text-muted-foreground py-8">No usage recorded yet.</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>
    </>
  );
};

ServicesPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default ServicesPage;
