import { useTranslation } from 'react-i18next';
import { ExternalLink } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { SettingsCard } from './SettingsCard';
import { useFormatPrefs, formatDate } from '@/lib/date';

const TIER_FEATURES: Record<string, string[]> = {
  free: ['20 req/min', '1 active agent', '0 GB cloud storage'],
  pro: ['60 req/min', '5 active agents', '5 GB cloud storage'],
  power: ['120 req/min', 'Unlimited agents', '25 GB cloud storage', 'Plugin marketplace'],
  team: ['200 req/min', 'Unlimited agents', 'Unlimited storage', 'Plugin marketplace'],
};

export function BillingSection() {
  const { t } = useTranslation();
  const prefs = useFormatPrefs();
  const authStatusQuery = trpc.auth.status.useQuery(undefined, { staleTime: 5 * 60 * 1000 });
  const subscriptionQuery = trpc.auth.getSubscription.useQuery();
  const invoicesQuery = trpc.auth.listInvoices.useQuery();
  const createCheckoutMutation = trpc.auth.createCheckout.useMutation();
  const cancelSubscriptionMutation = trpc.auth.cancelSubscription.useMutation();
  const utils = trpc.useUtils();
  const { notify, notifyError } = useNotify();

  const tier = (authStatusQuery.data?.profile?.tier as string) ?? 'free';
  const subscription = subscriptionQuery.data as Record<string, unknown> | undefined;
  const invoices = (invoicesQuery.data ?? []) as Record<string, unknown>[];

  function handleUpgrade(targetTier: string) {
    createCheckoutMutation.mutate(
      { tier: targetTier },
      {
        onSuccess: (data) => {
          const url = (data as { checkoutUrl: string }).checkoutUrl;
          if (url) window.open(url, '_blank');
        },
        onError: (err) => notifyError('settings.billingError', err),
      },
    );
  }

  function handleCancel() {
    cancelSubscriptionMutation.mutate(undefined, {
      onSuccess: () => {
        notify('info', 'settings.subscriptionCanceled');
        void subscriptionQuery.refetch();
        void utils.auth.status.invalidate();
      },
      onError: (err) => notifyError('settings.billingError', err),
    });
  }

  return (
    <>
      {/* Current plan */}
      <SettingsCard title={t('settings.currentPlan')}>
        <div className="flex flex-col gap-4">
          <div className="flex items-center gap-3">
            <Badge className="capitalize text-sm px-3 py-1">{tier}</Badge>
            {subscription?.status === 'active' && !!subscription?.currentPeriodEnd && (
              <span className="text-xs text-muted-foreground">
                {t('settings.renewsOn')} {formatDate(subscription.currentPeriodEnd as number, prefs)}
              </span>
            )}
          </div>

          <ul className="text-sm text-muted-foreground flex flex-col gap-1">
            {(TIER_FEATURES[tier] ?? []).map((f) => (
              <li key={f} className="flex items-center gap-2">
                <span className="size-1.5 rounded-full bg-primary shrink-0" />
                {f}
              </li>
            ))}
          </ul>

          {tier === 'free' && (
            <div className="flex gap-2">
              <Button size="sm" onClick={() => handleUpgrade('pro')} disabled={createCheckoutMutation.isPending}>
                {t('settings.upgradeTo')} Pro
              </Button>
              <Button size="sm" variant="outline" onClick={() => handleUpgrade('power')} disabled={createCheckoutMutation.isPending}>
                {t('settings.upgradeTo')} Power
              </Button>
            </div>
          )}

          {tier !== 'free' && subscription?.status === 'active' && (
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="outline" size="sm" className="w-fit text-destructive">
                  {t('settings.cancelSubscription')}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>{t('settings.cancelSubscriptionConfirm')}</AlertDialogTitle>
                  <AlertDialogDescription>{t('settings.cancelSubscriptionDescription')}</AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
                  <AlertDialogAction onClick={handleCancel} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                    {t('settings.cancelSubscription')}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          )}
        </div>
      </SettingsCard>

      <Separator />

      {/* Invoices */}
      <SettingsCard title={t('settings.billingHistory')}>
        {invoicesQuery.isLoading ? (
          <div className="flex flex-col gap-2">
            <Skeleton className="h-8 w-full" />
            <Skeleton className="h-8 w-full" />
            <Skeleton className="h-8 w-full" />
          </div>
        ) : invoices.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t('settings.noInvoices')}</p>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t('settings.invoiceDate')}</TableHead>
                <TableHead>{t('settings.invoiceAmount')}</TableHead>
                <TableHead>{t('settings.invoiceStatus')}</TableHead>
                <TableHead />
              </TableRow>
            </TableHeader>
            <TableBody>
              {invoices.map((inv) => (
                <TableRow key={inv.id as string}>
                  <TableCell className="text-sm">
                    {formatDate(inv.created as number, prefs)}
                  </TableCell>
                  <TableCell className="text-sm">
                    {((inv.amountPaid as number) / 100).toFixed(2)} {(inv.currency as string).toUpperCase()}
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className="capitalize">{String(inv.status)}</Badge>
                  </TableCell>
                  <TableCell>
                    {!!inv.invoiceUrl && (
                      <a href={inv.invoiceUrl as string} target="_blank" rel="noopener noreferrer">
                        <ExternalLink className="size-4 text-muted-foreground hover:text-foreground" />
                      </a>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </SettingsCard>
    </>
  );
}
