import { useState, useEffect, useCallback } from 'react';
import { DataTable } from '../../components/ui/DataTable';
import { BookingStatusBadge } from '../../components/rentals/BookingStatusBadge';
import { api } from '../../api/client';
import { formatCurrency } from '../../utils/format';
import type { Booking, BookingStatus } from '../../types/rental';

const STATUS_TABS: (BookingStatus | 'ALL')[] = ['ALL', 'PENDING', 'CONFIRMED', 'ACTIVE', 'COMPLETED', 'CANCELLED_BY_TENANT', 'CANCELLED_BY_LANDLORD', 'REJECTED', 'EXPIRED'];

export function AdminBookingsPage() {
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [tab, setTab] = useState<BookingStatus | 'ALL'>('ALL');

  const fetchBookings = useCallback(async () => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    if (search) params.set('search', search);
    if (tab !== 'ALL') params.set('status', tab);

    try {
      const res = await api.get<{ data: Booking[]; total: number }>(`/admin/bookings?${params}`);
      setBookings(res.data);
      setTotal(res.total);
    } catch {
      setBookings([]);
    }
  }, [page, search, tab]);

  useEffect(() => {
    fetchBookings();
  }, [fetchBookings]);

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-4">All Bookings</h1>

      {/* Status filter tabs */}
      <div className="flex gap-2 mb-4 flex-wrap">
        {STATUS_TABS.map((t) => (
          <button
            key={t}
            onClick={() => { setTab(t); setPage(1); }}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors cursor-pointer ${
              tab === t ? 'bg-primary-100 text-primary-700' : 'text-gray-500 hover:bg-gray-100'
            }`}
          >
            {t.replace(/_/g, ' ')}
          </button>
        ))}
      </div>

      <DataTable
        columns={[
          {
            key: 'rental',
            header: 'Rental',
            render: (b: Booking) => (
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-gray-100 overflow-hidden flex-shrink-0">
                  {b.rentalListing.images[0] ? (
                    <img src={b.rentalListing.images[0].url} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full bg-gray-200" />
                  )}
                </div>
                <div>
                  <p className="font-medium text-gray-900 truncate max-w-xs">{b.rentalListing.title}</p>
                  <p className="text-xs text-gray-400">{b.rentalListing.location}</p>
                </div>
              </div>
            ),
          },
          {
            key: 'tenant',
            header: 'Tenant',
            render: (b: Booking) => (
              <div>
                <p className="text-sm font-medium text-gray-900">{b.tenant.fullName}</p>
              </div>
            ),
          },
          {
            key: 'landlord',
            header: 'Landlord',
            render: (b: Booking) => (
              <div>
                <p className="text-sm font-medium text-gray-900">{b.landlord.fullName}</p>
              </div>
            ),
          },
          {
            key: 'dates',
            header: 'Dates',
            render: (b: Booking) => (
              <div className="text-sm">
                <p>{new Date(b.startDate).toLocaleDateString()} - {new Date(b.endDate).toLocaleDateString()}</p>
                <p className="text-xs text-gray-400">{b.totalPeriods} {b.periodType === 'DAILY' ? 'day(s)' : 'month(s)'}</p>
              </div>
            ),
          },
          {
            key: 'total',
            header: 'Total',
            render: (b: Booking) => <span className="font-medium">{formatCurrency(b.totalAmount)}</span>,
          },
          {
            key: 'status',
            header: 'Status',
            render: (b: Booking) => <BookingStatusBadge status={b.status} />,
          },
          {
            key: 'createdAt',
            header: 'Created',
            render: (b: Booking) => new Date(b.createdAt).toLocaleDateString(),
          },
        ]}
        data={bookings}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        searchValue={search}
        onSearch={(v) => { setSearch(v); setPage(1); }}
        searchPlaceholder="Search bookings..."
      />
    </div>
  );
}
