import { ReactNode, useMemo } from 'react';
import { Head } from '@inertiajs/react';
import AdminLayout from '@/layouts/AdminLayout';
import { useAuth } from '@/hooks/useAuth';
import { useQuery } from '@tanstack/react-query';
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 { GraduationCap, TrendingUp, Building2 } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { format, subMonths, startOfMonth, endOfMonth } from 'date-fns';
import { grossCents } from '@/lib/vat';

const fmtGBP = (cents: number) => `£${(cents / 100).toLocaleString('en-GB', { minimumFractionDigits: 2 })}`;

// Provider Courses & Revenue — moved from the old /company-portal. Shows a
// training/hybrid company's listed courses, trainers and booking revenue. Data
// comes from the company-scoped /api/training-companies/{id}/provider-* endpoints.
const ProviderHubPage = () => {
  const { companyId } = useAuth();

  const { data: company } = useQuery({
    queryKey: ['provider-hub-company-type', companyId],
    enabled: !!companyId,
    queryFn: async () => {
      const res = await fetch(`/api/companies/${companyId}/type`);
      if (!res.ok) return null;
      return res.json() as Promise<{ company_type: string } | null>;
    },
  });

  const isProvider = company?.company_type === 'training_company' || company?.company_type === 'hybrid';

  const { data: providerCourses } = useQuery({
    queryKey: ['provider-hub-courses', companyId],
    enabled: !!companyId && isProvider,
    queryFn: async () => {
      const res = await fetch(`/api/training-companies/${encodeURIComponent(companyId!)}/provider-courses`);
      if (!res.ok) return [];
      const data = await res.json();
      return ((data?.data ?? data) as any[]) || [];
    },
  });

  const { data: providerOrders } = useQuery({
    queryKey: ['provider-hub-orders', companyId],
    enabled: !!companyId && isProvider,
    queryFn: async () => {
      const res = await fetch(`/api/training-companies/${encodeURIComponent(companyId!)}/provider-orders`);
      if (!res.ok) return [];
      const data = await res.json();
      return ((data?.data ?? data) as any[]) || [];
    },
  });

  const { data: providerTrainers } = useQuery({
    queryKey: ['provider-hub-trainers', companyId],
    enabled: !!companyId && isProvider,
    queryFn: async () => {
      const res = await fetch(`/api/training-companies/${encodeURIComponent(companyId!)}/provider-trainers`);
      if (!res.ok) return [];
      const data = await res.json();
      return ((data?.data ?? data) as any[]) || [];
    },
  });

  const providerConfirmed = providerOrders?.filter((o: any) => ['paid', 'confirmed'].includes(o.status)) || [];
  const providerRevenue = providerConfirmed.reduce((s: number, o: any) => s + grossCents(o.price_cents), 0);

  const providerChartData = useMemo(() => {
    if (!providerOrders) return [];
    const months: { month: string; revenue: number }[] = [];
    for (let i = 5; i >= 0; i--) {
      const d = subMonths(new Date(), i);
      const start = startOfMonth(d);
      const end = endOfMonth(d);
      const monthOrders = providerOrders.filter((o: any) => {
        const created = new Date(o.created_at);
        return created >= start && created <= end && ['paid', 'confirmed'].includes(o.status);
      });
      months.push({
        month: format(d, 'MMM yy'),
        revenue: monthOrders.reduce((s: number, o: any) => s + grossCents(o.price_cents), 0) / 100,
      });
    }
    return months;
  }, [providerOrders]);

  return (
    <>
      <Head title="Provider Courses & Revenue" />
      <div>
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <GraduationCap className="h-6 w-6" /> Provider Courses &amp; Revenue
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Your listed courses, trainers, and the bookings they've generated.
          </p>
        </div>

        {!companyId ? (
          <Card>
            <CardContent className="py-16 text-center text-muted-foreground">
              Your account isn't linked to a company yet.
            </CardContent>
          </Card>
        ) : !company ? (
          <Card><CardContent className="py-16 text-center text-muted-foreground">Loading…</CardContent></Card>
        ) : !isProvider ? (
          <Card>
            <CardContent className="py-16 text-center">
              <div className="mx-auto w-14 h-14 rounded-full bg-muted flex items-center justify-center mb-3">
                <Building2 className="h-7 w-7 text-muted-foreground" />
              </div>
              <p className="text-sm font-semibold text-foreground mb-1">For training providers</p>
              <p className="text-sm text-muted-foreground">
                This section is only available to training/hybrid companies that list their own courses.
              </p>
            </CardContent>
          </Card>
        ) : (
          <>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6">
              <Card><CardContent className="py-4"><p className="text-xs text-muted-foreground">Courses Listed</p><p className="text-xl font-bold text-foreground">{providerCourses?.length || 0}</p></CardContent></Card>
              <Card><CardContent className="py-4"><p className="text-xs text-muted-foreground">Bookings Received</p><p className="text-xl font-bold text-foreground">{providerConfirmed.length}</p></CardContent></Card>
              <Card><CardContent className="py-4"><p className="text-xs text-muted-foreground">Total Revenue</p><p className="text-xl font-bold text-foreground">{fmtGBP(providerRevenue)}</p></CardContent></Card>
            </div>

            <Card className="mb-6">
              <CardHeader className="flex flex-row items-center gap-2">
                <TrendingUp className="h-5 w-5 text-primary" />
                <CardTitle>Revenue (Last 6 Months)</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={providerChartData}>
                      <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                      <XAxis dataKey="month" className="text-muted-foreground" fontSize={12} />
                      <YAxis className="text-muted-foreground" fontSize={12} tickFormatter={(v) => `£${v}`} />
                      <Tooltip formatter={(value: number) => [`£${value.toFixed(2)}`, 'Revenue']} />
                      <Bar dataKey="revenue" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader><CardTitle>Your Listed Courses</CardTitle></CardHeader>
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Title</TableHead>
                      <TableHead>Category</TableHead>
                      <TableHead>Duration</TableHead>
                      <TableHead>Price</TableHead>
                      <TableHead>Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {providerCourses?.map((c: any) => (
                      <TableRow key={c.id}>
                        <TableCell className="font-medium">{c.title}</TableCell>
                        <TableCell className="text-sm text-muted-foreground">{c.category}</TableCell>
                        <TableCell>{c.days} day{c.days > 1 ? 's' : ''}</TableCell>
                        <TableCell>{fmtGBP(c.price_cents)}</TableCell>
                        <TableCell><Badge variant={c.is_active ? 'default' : 'secondary'}>{c.is_active ? 'Active' : 'Inactive'}</Badge></TableCell>
                      </TableRow>
                    ))}
                    {!providerCourses?.length && (
                      <TableRow><TableCell colSpan={5} className="text-center text-muted-foreground py-8">No courses assigned yet.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>

            {providerTrainers && providerTrainers.length > 0 && (
              <Card className="mt-4">
                <CardHeader><CardTitle>Your Trainers</CardTitle></CardHeader>
                <CardContent className="p-0">
                  <Table>
                    <TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Email</TableHead><TableHead>Phone</TableHead></TableRow></TableHeader>
                    <TableBody>
                      {providerTrainers.map((t: any) => (
                        <TableRow key={t.id}>
                          <TableCell className="font-medium">{t.first_name} {t.last_name}</TableCell>
                          <TableCell className="text-sm text-muted-foreground">{t.email || '—'}</TableCell>
                          <TableCell className="text-sm text-muted-foreground">{t.phone || '—'}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            )}
          </>
        )}
      </div>
    </>
  );
};

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

export default ProviderHubPage;
