import Link from 'next/link';

import { ArrowLeft, Send, Users } from 'lucide-react';

import { createNewsletterApi } from '@kit/newsletter/api';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';

import { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';
import { StatsCard } from '~/components/stats-card';
import {
  NEWSLETTER_STATUS_VARIANT,
  NEWSLETTER_STATUS_LABEL,
  NEWSLETTER_RECIPIENT_STATUS_VARIANT,
  NEWSLETTER_RECIPIENT_STATUS_LABEL,
} from '~/lib/status-badges';

import { DispatchNewsletterButton } from './dispatch-newsletter-button';

interface PageProps {
  params: Promise<{ account: string; campaignId: string }>;
}

export default async function NewsletterDetailPage({ params }: PageProps) {
  const { account, campaignId } = await params;
  const client = getSupabaseServerClient();

  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!acct) return <AccountNotFound />;

  const api = createNewsletterApi(client);

  const [newsletter, recipients] = await Promise.all([
    api.getNewsletter(campaignId),
    api.getRecipients(campaignId),
  ]);

  if (!newsletter) return <AccountNotFound />;

  const status = String(newsletter.status);
  const sentCount = recipients.filter(
    (r: Record<string, unknown>) => r.status === 'sent',
  ).length;
  const failedCount = recipients.filter(
    (r: Record<string, unknown>) =>
      r.status === 'failed' || r.status === 'bounced',
  ).length;

  return (
    <CmsPageShell account={account} title="Newsletter Details">
      <div className="flex w-full flex-col gap-6">
        {/* Back link */}
        <div>
          <Link
            href={`/home/${account}/newsletter`}
            className="text-muted-foreground hover:text-foreground inline-flex items-center text-sm"
            data-test="newsletter-back-link"
          >
            <ArrowLeft className="mr-1 h-4 w-4" />
            Zurück zu Newsletter
          </Link>
        </div>

        {/* Summary Card */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>
              {String(newsletter.subject ?? '(Kein Betreff)')}
            </CardTitle>
            <Badge variant={NEWSLETTER_STATUS_VARIANT[status] ?? 'secondary'}>
              {NEWSLETTER_STATUS_LABEL[status] ?? status}
            </Badge>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
              <StatsCard
                title="Empfänger"
                value={recipients.length}
                icon={<Users className="h-5 w-5" />}
              />
              <StatsCard
                title="Gesendet"
                value={sentCount}
                icon={<Send className="h-5 w-5" />}
              />
              <StatsCard
                title="Fehlgeschlagen"
                value={failedCount}
                icon={<Send className="h-5 w-5" />}
              />
            </div>

            {/* Actions */}
            {status === 'draft' && (
              <div className="mt-6">
                <DispatchNewsletterButton
                  newsletterId={campaignId}
                  recipientCount={recipients.length}
                />
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recipients Table */}
        <Card>
          <CardHeader>
            <CardTitle>Empfänger ({recipients.length})</CardTitle>
          </CardHeader>
          <CardContent>
            {recipients.length === 0 ? (
              <p className="text-muted-foreground py-8 text-center text-sm">
                Keine Empfänger hinzugefügt. Fügen Sie Empfänger aus Ihrer
                Mitgliederliste hinzu.
              </p>
            ) : (
              <div className="rounded-md border">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b">
                      <th className="p-3 text-left font-medium">Name</th>
                      <th className="p-3 text-left font-medium">E-Mail</th>
                      <th className="p-3 text-left font-medium">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recipients.map((recipient: Record<string, unknown>) => {
                      const rStatus = String(recipient.status ?? 'pending');
                      return (
                        <tr
                          key={String(recipient.id)}
                          className="hover:bg-muted/30 border-b"
                        >
                          <td className="p-3 font-medium">
                            {String(recipient.name ?? '—')}
                          </td>
                          <td className="p-3">
                            {String(recipient.email ?? '—')}
                          </td>
                          <td className="p-3">
                            <Badge
                              variant={
                                NEWSLETTER_RECIPIENT_STATUS_VARIANT[rStatus] ??
                                'secondary'
                              }
                            >
                              {NEWSLETTER_RECIPIENT_STATUS_LABEL[rStatus] ??
                                rStatus}
                            </Badge>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
