import Link from 'next/link';

interface SitePage {
  id: string;
  title: string;
  slug: string;
  is_published: boolean;
  is_homepage: boolean;
  updated_at: string | null;
}

import { Plus, Globe, FileText, Settings, ExternalLink } from 'lucide-react';
import { getTranslations } from 'next-intl/server';

import { formatDate } from '@kit/shared/dates';
import { createSiteBuilderApi } from '@kit/site-builder/api';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Button } from '@kit/ui/button';
import { Card, CardContent } from '@kit/ui/card';
import { cn } from '@kit/ui/utils';

import { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';
import { EmptyState } from '~/components/empty-state';

import { PublishToggleButton } from './publish-toggle-button';

interface Props {
  params: Promise<{ account: string }>;
}

export default async function SiteBuilderDashboard({ params }: Props) {
  const { account } = await params;
  const client = getSupabaseServerClient();
  const t = await getTranslations('siteBuilder');

  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();
  if (!acct) return <AccountNotFound />;

  const api = createSiteBuilderApi(client);
  const [pages, settings, posts] = await Promise.all([
    api.listPages(acct.id),
    api.getSiteSettings(acct.id),
    api.listPosts(acct.id),
  ]);

  const isOnline = Boolean(settings?.is_public);
  const publishedCount = (pages as SitePage[]).filter(
    (p) => p.is_published,
  ).length;

  return (
    <CmsPageShell
      account={account}
      title={t('dashboard.title')}
      description={t('dashboard.description')}
    >
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex gap-2">
            <Button variant="outline" size="sm" asChild>
              <Link href={`/home/${account}/site-builder/settings`}>
                <Settings className="mr-2 h-4 w-4" />
                {t('dashboard.btnSettings')}
              </Link>
            </Button>
            <Button variant="outline" size="sm" asChild>
              <Link href={`/home/${account}/site-builder/posts`}>
                <FileText className="mr-2 h-4 w-4" />
                {t('dashboard.btnPosts', { count: posts.length })}
              </Link>
            </Button>
            {isOnline && (
              <Button variant="outline" size="sm" asChild>
                <a href={`/club/${account}`} target="_blank" rel="noopener">
                  <ExternalLink className="mr-2 h-4 w-4" />
                  {t('site.viewSite')}
                </a>
              </Button>
            )}
          </div>
          <Button data-test="site-new-page-btn" asChild>
            <Link href={`/home/${account}/site-builder/new`}>
              <Plus className="mr-2 h-4 w-4" />
              {t('pages.newPage')}
            </Link>
          </Button>
        </div>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          <Card>
            <CardContent className="p-6">
              <p className="text-muted-foreground text-sm">
                {t('site.stats.pages')}
              </p>
              <p className="text-2xl font-bold">{pages.length}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <p className="text-muted-foreground text-sm">
                {t('site.stats.published')}
              </p>
              <p className="text-2xl font-bold">{publishedCount}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <p className="text-muted-foreground text-sm">
                {t('site.stats.status')}
              </p>
              <p className="text-2xl font-bold">
                <span className="flex items-center gap-1.5">
                  <span
                    className={cn(
                      'inline-block h-2 w-2 rounded-full',
                      isOnline ? 'bg-green-500' : 'bg-red-500',
                    )}
                  />
                  <span>
                    {isOnline ? t('pages.online') : t('pages.offline')}
                  </span>
                </span>
              </p>
            </CardContent>
          </Card>
        </div>

        {pages.length === 0 ? (
          <EmptyState
            icon={<Globe className="h-8 w-8" />}
            title={t('pages.noPagesYet')}
            description={t('pages.noPageDesc')}
            actionLabel={t('pages.firstPage')}
            actionHref={`/home/${account}/site-builder/new`}
          />
        ) : (
          <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('pages.colTitle')}
                  </th>
                  <th scope="col" className="p-3 text-left font-medium">
                    {t('pages.colUrl')}
                  </th>
                  <th scope="col" className="p-3 text-left font-medium">
                    {t('pages.colStatus')}
                  </th>
                  <th scope="col" className="p-3 text-left font-medium">
                    {t('pages.colHomepage')}
                  </th>
                  <th scope="col" className="p-3 text-left font-medium">
                    {t('pages.colUpdated')}
                  </th>
                  <th scope="col" className="p-3 text-left font-medium">
                    {t('pages.colActions')}
                  </th>
                </tr>
              </thead>
              <tbody>
                {(pages as SitePage[]).map((page) => (
                  <tr key={page.id} className="hover:bg-muted/30 border-b">
                    <td className="p-3 font-medium">{page.title}</td>
                    <td className="text-muted-foreground p-3 font-mono text-xs">
                      /{page.slug}
                    </td>
                    <td className="p-3">
                      <Badge
                        variant={page.is_published ? 'default' : 'secondary'}
                      >
                        {page.is_published
                          ? t('pages.statusPublished')
                          : t('pages.statusDraft')}
                      </Badge>
                    </td>
                    <td className="p-3">
                      {page.is_homepage ? (
                        <span className="text-xs font-medium text-amber-600">
                          {t('pages.homepageLabel')}
                        </span>
                      ) : (
                        '—'
                      )}
                    </td>
                    <td className="text-muted-foreground p-3 text-xs">
                      {formatDate(page.updated_at)}
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        <PublishToggleButton
                          pageId={page.id}
                          accountId={acct.id}
                          isPublished={page.is_published}
                        />
                        <Button size="sm" variant="outline" asChild>
                          <Link
                            href={`/home/${account}/site-builder/${page.id}/edit`}
                          >
                            {t('pages.edit')}
                          </Link>
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </CmsPageShell>
  );
}
