import Link from 'next/link';

import { BedDouble, CalendarCheck, Plus, Euro } 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 { createBookingManagementApi } from '@kit/booking-management/api';

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

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

const STATUS_BADGE_VARIANT: Record<
  string,
  'secondary' | 'default' | 'info' | 'outline' | 'destructive'
> = {
  pending: 'secondary',
  confirmed: 'default',
  checked_in: 'info',
  checked_out: 'outline',
  cancelled: 'destructive',
};

const STATUS_LABEL: Record<string, string> = {
  pending: 'Ausstehend',
  confirmed: 'Bestätigt',
  checked_in: 'Eingecheckt',
  checked_out: 'Ausgecheckt',
  cancelled: 'Storniert',
  no_show: 'Nicht erschienen',
};

export default async function BookingsPage({ params }: PageProps) {
  const { account } = 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 = createBookingManagementApi(client);

  const [rooms, bookings] = await Promise.all([
    api.listRooms(acct.id),
    api.listBookings(acct.id, { page: 1 }),
  ]);

  const activeBookings = bookings.data.filter(
    (b: Record<string, unknown>) =>
      b.status === 'confirmed' || b.status === 'checked_in',
  );

  return (
    <CmsPageShell account={account} title="Buchungen">
      <div className="flex w-full flex-col gap-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold">Buchungen</h1>
            <p className="text-muted-foreground">
              Zimmer und Buchungen verwalten
            </p>
          </div>

          <Link href={`/home/${account}/bookings/new`}>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Neue Buchung
            </Button>
          </Link>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <StatsCard
            title="Zimmer"
            value={rooms.length}
            icon={<BedDouble className="h-5 w-5" />}
          />
          <StatsCard
            title="Aktive Buchungen"
            value={activeBookings.length}
            icon={<CalendarCheck className="h-5 w-5" />}
          />
          <StatsCard
            title="Gesamt"
            value={bookings.total}
            icon={<Euro className="h-5 w-5" />}
          />
        </div>

        {/* Table or Empty State */}
        {bookings.data.length === 0 ? (
          <EmptyState
            icon={<BedDouble className="h-8 w-8" />}
            title="Keine Buchungen vorhanden"
            description="Erstellen Sie Ihre erste Buchung, um loszulegen."
            actionLabel="Neue Buchung"
            actionHref={`/home/${account}/bookings/new`}
          />
        ) : (
          <Card>
            <CardHeader>
              <CardTitle>Alle Buchungen ({bookings.total})</CardTitle>
            </CardHeader>
            <CardContent>
              <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">Zimmer</th>
                      <th className="p-3 text-left font-medium">Gast</th>
                      <th className="p-3 text-left font-medium">Anreise</th>
                      <th className="p-3 text-left font-medium">Abreise</th>
                      <th className="p-3 text-left font-medium">Status</th>
                      <th className="p-3 text-right font-medium">Betrag</th>
                    </tr>
                  </thead>
                  <tbody>
                    {bookings.data.map((booking: Record<string, unknown>) => (
                      <tr
                        key={String(booking.id)}
                        className="border-b hover:bg-muted/30"
                      >
                        <td className="p-3">
                          <Link
                            href={`/home/${account}/bookings/${String(booking.id)}`}
                            className="font-medium hover:underline"
                          >
                            {String(booking.room_id ?? '—')}
                          </Link>
                        </td>
                        <td className="p-3">
                          {String(booking.guest_id ?? '—')}
                        </td>
                        <td className="p-3">
                          {booking.check_in
                            ? new Date(String(booking.check_in)).toLocaleDateString('de-DE')
                            : '—'}
                        </td>
                        <td className="p-3">
                          {booking.check_out
                            ? new Date(String(booking.check_out)).toLocaleDateString('de-DE')
                            : '—'}
                        </td>
                        <td className="p-3">
                          <Badge
                            variant={
                              STATUS_BADGE_VARIANT[String(booking.status)] ?? 'secondary'
                            }
                          >
                            {STATUS_LABEL[String(booking.status)] ?? String(booking.status)}
                          </Badge>
                        </td>
                        <td className="p-3 text-right">
                          {booking.total_price != null
                            ? `${Number(booking.total_price).toFixed(2)} €`
                            : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </CmsPageShell>
  );
}
