import Link from 'next/link';

import { ArrowLeft, ChevronLeft, ChevronRight } 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 { AccountNotFound } from '~/components/account-not-found';

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

const WEEKDAYS = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];

const MONTH_NAMES = [
  'Januar',
  'Februar',
  'März',
  'April',
  'Mai',
  'Juni',
  'Juli',
  'August',
  'September',
  'Oktober',
  'November',
  'Dezember',
];

function getDaysInMonth(year: number, month: number): number {
  return new Date(year, month + 1, 0).getDate();
}

function getFirstWeekday(year: number, month: number): number {
  const day = new Date(year, month, 1).getDay();
  // Convert Sunday=0 to Monday-based (Mo=0, Di=1 … So=6)
  return day === 0 ? 6 : day - 1;
}

function isDateInRange(date: string, checkIn: string, checkOut: string): boolean {
  return date >= checkIn && date < checkOut;
}

export default async function BookingCalendarPage({ 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 (
      <CmsPageShell account={account} title="Belegungskalender">
        <AccountNotFound />
      </CmsPageShell>
    );
  }

  const api = createBookingManagementApi(client);

  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth();
  const daysInMonth = getDaysInMonth(year, month);
  const firstWeekday = getFirstWeekday(year, month);

  // Load bookings for this month
  const monthStart = `${year}-${String(month + 1).padStart(2, '0')}-01`;
  const monthEnd = `${year}-${String(month + 1).padStart(2, '0')}-${String(daysInMonth).padStart(2, '0')}`;

  const bookings = await api.listBookings(acct.id, {
    from: monthStart,
    to: monthEnd,
    page: 1,
  });

  // Build set of occupied dates
  const occupiedDates = new Set<string>();
  for (const booking of bookings.data) {
    const b = booking as Record<string, unknown>;
    if (b.status === 'cancelled' || b.status === 'no_show') continue;
    const checkIn = String(b.check_in ?? '');
    const checkOut = String(b.check_out ?? '');
    if (!checkIn || !checkOut) continue;

    for (let d = 1; d <= daysInMonth; d++) {
      const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
      if (isDateInRange(dateStr, checkIn, checkOut)) {
        occupiedDates.add(dateStr);
      }
    }
  }

  // Build calendar grid cells
  const cells: Array<{ day: number | null; occupied: boolean; isToday: boolean }> = [];

  // Empty cells before first day
  for (let i = 0; i < firstWeekday; i++) {
    cells.push({ day: null, occupied: false, isToday: false });
  }

  const todayStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;

  for (let d = 1; d <= daysInMonth; d++) {
    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
    cells.push({
      day: d,
      occupied: occupiedDates.has(dateStr),
      isToday: dateStr === todayStr,
    });
  }

  // Fill remaining cells to complete the grid
  while (cells.length % 7 !== 0) {
    cells.push({ day: null, occupied: false, isToday: false });
  }

  return (
    <CmsPageShell account={account} title="Belegungskalender">
      <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>
            <p className="text-muted-foreground">
              Zimmerauslastung im Überblick
            </p>
          </div>
        </div>

        {/* Month Navigation */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <Button variant="ghost" size="icon" disabled>
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <CardTitle>
                {MONTH_NAMES[month]} {year}
              </CardTitle>
              <Button variant="ghost" size="icon" disabled>
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {/* Weekday Header */}
            <div className="grid grid-cols-7 gap-1 mb-1">
              {WEEKDAYS.map((day) => (
                <div
                  key={day}
                  className="text-center text-xs font-medium text-muted-foreground py-2"
                >
                  {day}
                </div>
              ))}
            </div>

            {/* Calendar Grid */}
            <div className="grid grid-cols-7 gap-1">
              {cells.map((cell, idx) => (
                <div
                  key={idx}
                  className={`relative flex h-12 items-center justify-center rounded-md text-sm transition-colors ${
                    cell.day === null
                      ? 'bg-transparent'
                      : cell.occupied
                        ? 'bg-primary/15 text-primary font-semibold'
                        : 'bg-muted/30 hover:bg-muted/50'
                  } ${cell.isToday ? 'ring-2 ring-primary ring-offset-1' : ''}`}
                >
                  {cell.day !== null && (
                    <>
                      <span>{cell.day}</span>
                      {cell.occupied && (
                        <span className="absolute bottom-1 left-1/2 -translate-x-1/2 h-1.5 w-1.5 rounded-full bg-primary" />
                      )}
                    </>
                  )}
                </div>
              ))}
            </div>

            {/* Legend */}
            <div className="mt-4 flex items-center gap-4 text-xs text-muted-foreground">
              <div className="flex items-center gap-1.5">
                <span className="inline-block h-3 w-3 rounded-sm bg-primary/15" />
                Belegt
              </div>
              <div className="flex items-center gap-1.5">
                <span className="inline-block h-3 w-3 rounded-sm bg-muted/30" />
                Frei
              </div>
              <div className="flex items-center gap-1.5">
                <span className="inline-block h-3 w-3 rounded-sm ring-2 ring-primary" />
                Heute
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Summary */}
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">
                  Buchungen in diesem Monat
                </p>
                <p className="text-2xl font-bold">{bookings.data.length}</p>
              </div>
              <Badge variant="outline">
                {occupiedDates.size} von {daysInMonth} Tagen belegt
              </Badge>
            </div>
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
