import Link from 'next/link';

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

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 { createNewsletterApi } from '@kit/newsletter/api';

import { CmsPageShell } from '~/components/cms-page-shell';
import { StatsCard } from '~/components/stats-card';

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

const STATUS_VARIANT: Record<
  string,
  'secondary' | 'default' | 'info' | 'outline' | 'destructive'
> = {
  draft: 'secondary',
  scheduled: 'default',
  sending: 'info',
  sent: 'outline',
  failed: 'destructive',
};

const STATUS_LABEL: Record<string, string> = {
  draft: 'Entwurf',
  scheduled: 'Geplant',
  sending: 'Wird gesendet',
  sent: 'Gesendet',
  failed: 'Fehlgeschlagen',
};

const RECIPIENT_STATUS_VARIANT: Record<
  string,
  'secondary' | 'default' | 'info' | 'outline' | 'destructive'
> = {
  pending: 'secondary',
  sent: 'default',
  failed: 'destructive',
  bounced: 'destructive',
};

const RECIPIENT_STATUS_LABEL: Record<string, string> = {
  pending: 'Ausstehend',
  sent: 'Gesendet',
  failed: 'Fehlgeschlagen',
  bounced: 'Zurückgewiesen',
};

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 <div>Konto nicht gefunden</div>;

  const api = createNewsletterApi(client);

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

  if (!newsletter) return <div>Newsletter nicht gefunden</div>;

  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"
          >
            <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={STATUS_VARIANT[status] ?? 'secondary'}>
              {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">
                <Button>
                  <Send className="mr-2 h-4 w-4" />
                  Newsletter versenden
                </Button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recipients Table */}
        <Card>
          <CardHeader>
            <CardTitle>Empfänger ({recipients.length})</CardTitle>
          </CardHeader>
          <CardContent>
            {recipients.length === 0 ? (
              <p className="py-8 text-center text-sm text-muted-foreground">
                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="border-b bg-muted/50">
                      <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="border-b hover:bg-muted/30"
                        >
                          <td className="p-3 font-medium">
                            {String(recipient.name ?? '—')}
                          </td>
                          <td className="p-3">
                            {String(recipient.email ?? '—')}
                          </td>
                          <td className="p-3">
                            <Badge
                              variant={
                                RECIPIENT_STATUS_VARIANT[rStatus] ?? 'secondary'
                              }
                            >
                              {RECIPIENT_STATUS_LABEL[rStatus] ?? rStatus}
                            </Badge>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
