﻿import React from 'react';
import { Loader2, RefreshCw, Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';

import { AdminLayout } from '../components/AdminLayout';
import { getTenantPackagesOverview, TenantPackageSummary } from '../api';
import { isAuthError } from '../auth/tokens';

export default function BillingPage() {
  const { t, i18n } = useTranslation(['management', 'dashboard']);
  const locale = React.useMemo(
    () => (i18n.language?.startsWith('en') ? 'en-GB' : 'de-DE'),
    [i18n.language]
  );

  const [packages, setPackages] = React.useState<TenantPackageSummary[]>([]);
  const [activePackage, setActivePackage] = React.useState<TenantPackageSummary | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  const formatDate = React.useCallback(
    (value: string | null | undefined) => {
      if (!value) return '--';
      const date = new Date(value);
      if (Number.isNaN(date.getTime())) return '--';
      return date.toLocaleDateString(locale, { day: '2-digit', month: 'short', year: 'numeric' });
    },
    [locale]
  );

  const formatCurrency = React.useCallback(
    (value: number | null | undefined, currency = 'EUR') => {
      if (value === null || value === undefined) return '--';
      return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value);
    },
    [locale]
  );

  const packageLabels = React.useMemo(
    () => ({
      statusActive: t('billing.sections.packages.card.statusActive'),
      statusInactive: t('billing.sections.packages.card.statusInactive'),
      used: t('billing.sections.packages.card.used'),
      available: t('billing.sections.packages.card.available'),
      expires: t('billing.sections.packages.card.expires'),
    }),
    [t]
  );

  const loadAll = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const packagesResult = await getTenantPackagesOverview();
      setPackages(packagesResult.packages);
      setActivePackage(packagesResult.activePackage);
    } catch (err) {
      if (!isAuthError(err)) {
        setError(t('billing.errors.load'));
      }
    } finally {
      setLoading(false);
    }
  }, [t]);

  React.useEffect(() => {
    void loadAll();
  }, [loadAll]);

  const actions = (
    <Button variant="outline" onClick={() => void loadAll()} disabled={loading}>
      {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
      {t('billing.actions.refresh')}
    </Button>
  );

  return (
    <AdminLayout
      title={t('billing.title')}
      subtitle={t('billing.subtitle')}
      actions={actions}
    >
      {error && (
        <Alert variant="destructive">
          <AlertTitle>{t('dashboard:alerts.errorTitle')}</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {loading ? (
        <BillingSkeleton />
      ) : (
        <>
          <Card className="border-0 bg-white/85 shadow-xl shadow-pink-100/60">
            <CardHeader className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
              <div>
                <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
                  <Sparkles className="h-5 w-5 text-pink-500" />
                  {t('billing.sections.overview.title')}
                </CardTitle>
                <CardDescription className="text-sm text-slate-600">
                  {t('billing.sections.overview.description')}
                </CardDescription>
              </div>
              <Badge className={activePackage ? 'bg-pink-500/10 text-pink-700' : 'bg-slate-200 text-slate-700'}>
                {activePackage ? activePackage.package_name : t('billing.sections.overview.emptyBadge')}
              </Badge>
            </CardHeader>
            <CardContent>
              {activePackage ? (
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                  <InfoCard
                    label={t('billing.sections.overview.cards.package.label')}
                    value={activePackage.package_name}
                    tone="pink"
                    helper={t('billing.sections.overview.cards.package.helper')}
                  />
                  <InfoCard
                    label={t('billing.sections.overview.cards.used.label')}
                    value={activePackage.used_events ?? 0}
                    tone="amber"
                    helper={t('billing.sections.overview.cards.used.helper', {
                      count: activePackage.remaining_events ?? 0,
                    })}
                  />
                  <InfoCard
                    label={t('billing.sections.overview.cards.price.label')}
                    value={formatCurrency(activePackage.price ?? null, activePackage.currency ?? 'EUR')}
                    tone="sky"
                    helper={activePackage.currency ?? 'EUR'}
                  />
                  <InfoCard
                    label={t('billing.sections.overview.cards.expires.label')}
                    value={formatDate(activePackage.expires_at)}
                    tone="emerald"
                    helper={t('billing.sections.overview.cards.expires.helper')}
                  />
                </div>
              ) : (
                <EmptyState message={t('billing.sections.overview.empty')} />
              )}
            </CardContent>
          </Card>

          <Card className="border-0 bg-white/85 shadow-xl shadow-amber-100/60">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
                <Sparkles className="h-5 w-5 text-amber-500" />
                {t('billing.sections.packages.title')}
              </CardTitle>
              <CardDescription className="text-sm text-slate-600">
                {t('billing.sections.packages.description')}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {packages.length === 0 ? (
                <EmptyState message={t('billing.sections.packages.empty')} />
              ) : (
                packages.map((pkg) => (
                  <PackageCard
                    key={pkg.id}
                    pkg={pkg}
                    isActive={Boolean(pkg.active)}
                    labels={packageLabels}
                    formatDate={formatDate}
                    formatCurrency={formatCurrency}
                  />
                ))
              )}
            </CardContent>
          </Card>

        </>
      )}
    </AdminLayout>
  );
}
function InfoCard({
  label,
  value,
  helper,
  tone,
}: {
  label: string;
  value: string | number | null | undefined;
  helper?: string;
  tone: 'pink' | 'amber' | 'sky' | 'emerald';
}) {
  const toneClass = {
    pink: 'from-pink-50 to-rose-100 text-pink-700',
    amber: 'from-amber-50 to-yellow-100 text-amber-700',
    sky: 'from-sky-50 to-blue-100 text-sky-700',
    emerald: 'from-emerald-50 to-green-100 text-emerald-700',
  }[tone];

  return (
    <div className={`rounded-2xl border border-white/60 bg-gradient-to-br ${toneClass} p-5 shadow-sm`}>
      <span className="text-xs uppercase tracking-wide text-slate-600/90">{label}</span>
      <div className="mt-3 text-xl font-semibold">{value ?? '--'}</div>
      {helper && <p className="mt-2 text-xs text-slate-600/80">{helper}</p>}
    </div>
  );
}

function PackageCard({
  pkg,
  isActive,
  labels,
  formatDate,
  formatCurrency,
}: {
  pkg: TenantPackageSummary;
  isActive: boolean;
  labels: {
    statusActive: string;
    statusInactive: string;
    used: string;
    available: string;
    expires: string;
  };
  formatDate: (value: string | null | undefined) => string;
  formatCurrency: (value: number | null | undefined, currency?: string) => string;
}) {
  return (
    <div className="rounded-2xl border border-amber-100 bg-white/90 p-4 shadow-sm">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h3 className="text-sm font-semibold text-slate-900">{pkg.package_name}</h3>
          <p className="text-xs text-slate-600">
            {formatDate(pkg.purchased_at)} · {formatCurrency(pkg.price, pkg.currency ?? 'EUR')}
          </p>
        </div>
        <Badge className={isActive ? 'bg-amber-500/10 text-amber-700' : 'bg-slate-200 text-slate-700'}>
          {isActive ? labels.statusActive : labels.statusInactive}
        </Badge>
      </div>
      <Separator className="my-3" />
      <div className="grid gap-2 text-xs text-slate-600 sm:grid-cols-3">
        <span>
          {labels.used}: {pkg.used_events}
        </span>
        <span>
          {labels.available}: {pkg.remaining_events ?? '--'}
        </span>
        <span>
          {labels.expires}: {formatDate(pkg.expires_at)}
        </span>
      </div>
    </div>
  );
}

function EmptyState({ message }: { message: string }) {
  return (
    <div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-slate-200 bg-white/70 p-8 text-center">
      <div className="rounded-full bg-pink-100 p-3 text-pink-600 shadow-inner shadow-pink-200/80">
        <Sparkles className="h-5 w-5" />
      </div>
      <p className="text-sm text-slate-600">{message}</p>
    </div>
  );
}

function BillingSkeleton() {
  return (
    <div className="grid gap-6">
      {Array.from({ length: 3 }).map((_, index) => (
        <div key={index} className="space-y-4 rounded-2xl border border-white/60 bg-white/70 p-6 shadow-sm">
          <div className="h-6 w-48 animate-pulse rounded bg-gradient-to-r from-white/40 via-white/60 to-white/40" />
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {Array.from({ length: 4 }).map((__, placeholderIndex) => (
              <div
                key={placeholderIndex}
                className="h-24 animate-pulse rounded-2xl bg-gradient-to-r from-white/40 via-white/60 to-white/40"
              />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}
