import Link from 'next/link';

import { ArrowLeft, Pencil, Send, Users } from 'lucide-react';
import { getTranslations } from 'next-intl/server';

import { createNewsletterApi } from '@kit/newsletter/api';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Button } from '@kit/ui/button';
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_KEYS,
  NEWSLETTER_RECIPIENT_STATUS_VARIANT,
  NEWSLETTER_RECIPIENT_STATUS_LABEL_KEYS,
} 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 t = await getTranslations('newsletter');

  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={t('detail.title')}>
      <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" />
            {t('detail.backToList')}
          </Link>
        </div>

        {/* Summary Card */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>
              {String(newsletter.subject ?? `(${t('list.noSubject')})`)}
            </CardTitle>
            <div className="flex items-center gap-2">
              {status === 'draft' && (
                <Button asChild variant="outline" size="sm">
                  <Link href={`/home/${account}/newsletter/${campaignId}/edit`}>
                    <Pencil className="mr-2 h-4 w-4" />
                    Bearbeiten
                  </Link>
                </Button>
              )}
              <Badge variant={NEWSLETTER_STATUS_VARIANT[status] ?? 'secondary'}>
                {t(NEWSLETTER_STATUS_LABEL_KEYS[status] ?? status)}
              </Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
              <StatsCard
                title={t('detail.recipientsSection')}
                value={recipients.length}
                icon={<Users className="h-5 w-5" />}
              />
              <StatsCard
                title={t('detail.sentCount')}
                value={sentCount}
                icon={<Send className="h-5 w-5" />}
              />
              <StatsCard
                title={t('detail.failedCount')}
                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>
              {t('detail.recipientsSection')} ({recipients.length})
            </CardTitle>
          </CardHeader>
          <CardContent>
            {recipients.length === 0 ? (
              <p className="text-muted-foreground py-8 text-center text-sm">
                {t('detail.noRecipients')}
              </p>
            ) : (
              <div className="overflow-x-auto rounded-md border">
                <table className="w-full min-w-[640px] text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b">
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('detail.recipientName')}
                      </th>
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('detail.recipientEmail')}
                      </th>
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('detail.recipientStatus')}
                      </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'
                              }
                            >
                              {t(NEWSLETTER_RECIPIENT_STATUS_LABEL_KEYS[rStatus] ?? rStatus)}
                            </Badge>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
