import Link from 'next/link';

import {
  ArrowLeft,
  BedDouble,
  CalendarDays,
  LogIn,
  LogOut,
  XCircle,
  User,
} from 'lucide-react';

import { formatDate } from '@kit/shared/dates';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Button } from '@kit/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@kit/ui/card';

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

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

const STATUS_BADGE_VARIANT: Record<
  string,
  'secondary' | 'default' | 'info' | 'outline' | 'destructive'
> = {
  pending: 'secondary',
  confirmed: 'default',
  checked_in: 'info',
  checked_out: 'outline',
  cancelled: 'destructive',
  no_show: '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 BookingDetailPage({ params }: PageProps) {
  const { account, bookingId } = await params;
  const client = getSupabaseServerClient();

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

  if (!acct) {
    return (
      <CmsPageShell account={account} title="Buchungsdetails">
        <AccountNotFound />
      </CmsPageShell>
    );
  }

  // Load booking directly
  const { data: booking } = await client
    .from('bookings')
    .select('*')
    .eq('id', bookingId)
    .eq('account_id', acct.id)
    .single();

  if (!booking) {
    return (
      <CmsPageShell account={account} title="Buchung nicht gefunden">
        <div className="flex flex-col items-center gap-4 py-12">
          <p className="text-muted-foreground">
            Buchung mit ID &quot;{bookingId}&quot; wurde nicht gefunden.
          </p>
          <Link href={`/home/${account}/bookings`}>
            <Button variant="outline">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Zurück zu Buchungen
            </Button>
          </Link>
        </div>
      </CmsPageShell>
    );
  }

  // Load related room and guest data
  const [roomResult, guestResult] = await Promise.all([
    booking.room_id
      ? client.from('rooms').select('*').eq('id', booking.room_id).single()
      : Promise.resolve({ data: null }),
    booking.guest_id
      ? client.from('guests').select('*').eq('id', booking.guest_id).single()
      : Promise.resolve({ data: null }),
  ]);

  const room = roomResult.data;
  const guest = guestResult.data;
  const status = String(booking.status ?? 'pending');

  return (
    <CmsPageShell account={account} title="Buchungsdetails">
      <div className="flex w-full flex-col gap-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href={`/home/${account}/bookings`}>
              <Button variant="ghost" size="icon">
                <ArrowLeft className="h-4 w-4" />
              </Button>
            </Link>
            <div>
              <div className="flex items-center gap-3">
                <Badge variant={STATUS_BADGE_VARIANT[status] ?? 'secondary'}>
                  {STATUS_LABEL[status] ?? status}
                </Badge>
              </div>
              <p className="text-muted-foreground text-sm">ID: {bookingId}</p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          {/* Zimmer */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <BedDouble className="h-5 w-5" />
                Zimmer
              </CardTitle>
            </CardHeader>
            <CardContent>
              {room ? (
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground text-sm">
                      Zimmernummer
                    </span>
                    <span className="font-medium">
                      {String(room.room_number)}
                    </span>
                  </div>
                  {room.name && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground text-sm">
                        Name
                      </span>
                      <span className="font-medium">{String(room.name)}</span>
                    </div>
                  )}
                  <div className="flex justify-between">
                    <span className="text-muted-foreground text-sm">Typ</span>
                    <span className="font-medium">
                      {String(room.room_type ?? '—')}
                    </span>
                  </div>
                </div>
              ) : (
                <p className="text-muted-foreground text-sm">
                  Kein Zimmer zugewiesen
                </p>
              )}
            </CardContent>
          </Card>

          {/* Gast */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <User className="h-5 w-5" />
                Gast
              </CardTitle>
            </CardHeader>
            <CardContent>
              {guest ? (
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground text-sm">Name</span>
                    <span className="font-medium">
                      {String(guest.first_name)} {String(guest.last_name)}
                    </span>
                  </div>
                  {guest.email && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground text-sm">
                        E-Mail
                      </span>
                      <span className="font-medium">{String(guest.email)}</span>
                    </div>
                  )}
                  {guest.phone && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground text-sm">
                        Telefon
                      </span>
                      <span className="font-medium">{String(guest.phone)}</span>
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-muted-foreground text-sm">
                  Kein Gast zugewiesen
                </p>
              )}
            </CardContent>
          </Card>

          {/* Aufenthalt */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <CalendarDays className="h-5 w-5" />
                Aufenthalt
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-muted-foreground text-sm">
                    Check-in
                  </span>
                  <span className="font-medium">
                    {formatDate(booking.check_in)}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground text-sm">
                    Check-out
                  </span>
                  <span className="font-medium">
                    {formatDate(booking.check_out)}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground text-sm">
                    Erwachsene
                  </span>
                  <span className="font-medium">{booking.adults ?? '—'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground text-sm">Kinder</span>
                  <span className="font-medium">{booking.children ?? 0}</span>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Betrag */}
          <Card>
            <CardHeader>
              <CardTitle>Betrag</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-muted-foreground text-sm">
                    Gesamtpreis
                  </span>
                  <span className="text-2xl font-bold">
                    {booking.total_price != null
                      ? `${Number(booking.total_price).toFixed(2)} €`
                      : '—'}
                  </span>
                </div>
                {booking.notes && (
                  <div className="border-t pt-2">
                    <span className="text-muted-foreground text-sm">
                      Notizen
                    </span>
                    <p className="mt-1 text-sm">{String(booking.notes)}</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Status Workflow */}
        <Card>
          <CardHeader>
            <CardTitle>Aktionen</CardTitle>
            <CardDescription>Status der Buchung ändern</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-3">
              {(status === 'pending' || status === 'confirmed') && (
                <Button variant="default">
                  <LogIn className="mr-2 h-4 w-4" />
                  Einchecken
                </Button>
              )}

              {status === 'checked_in' && (
                <Button variant="default">
                  <LogOut className="mr-2 h-4 w-4" />
                  Auschecken
                </Button>
              )}

              {status !== 'cancelled' &&
                status !== 'checked_out' &&
                status !== 'no_show' && (
                  <Button variant="destructive">
                    <XCircle className="mr-2 h-4 w-4" />
                    Stornieren
                  </Button>
                )}

              {status === 'cancelled' || status === 'checked_out' ? (
                <p className="text-muted-foreground py-2 text-sm">
                  Diese Buchung ist{' '}
                  {status === 'cancelled' ? 'storniert' : 'abgeschlossen'} —
                  keine weiteren Aktionen verfügbar.
                </p>
              ) : null}
            </div>
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
