import { useState, useEffect, useCallback } from 'react';
import { Check, X, CheckCircle } from 'lucide-react';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { api } from '../../api/client';
import type { Booking } from '../../types/rental';

const TABS = ['ALL', 'PENDING', 'ACTIVE', 'COMPLETED'] as const;

export function LandlordBookingsPage() {
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [tab, setTab] = useState<string>('ALL');

  const fetchBookings = useCallback(async () => {
    try {
      const params = new URLSearchParams({ role: 'landlord', page: String(page), pageSize: '20' });
      if (tab !== 'ALL') params.set('status', tab);
      const res = await api.get<Booking[]>(`/bookings?${params}`);
      setBookings(res);
      setTotal(res.length);
    } catch {
      // silently fail
    }
  }, [page, tab]);

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

  const handleAction = async (bookingId: string, action: 'confirm' | 'reject' | 'complete') => {
    try {
      if (action === 'reject') {
        const reason = window.prompt('Reason for rejection:');
        if (!reason) return;
        await api.patch(`/bookings/${bookingId}/${action}`, { reason });
      } else {
        await api.patch(`/bookings/${bookingId}/${action}`);
      }
      fetchBookings();
    } catch {
      // silently fail
    }
  };

  const statusBadge = (status: string) => {
    const map: Record<string, 'success' | 'warning' | 'info' | 'error' | 'default'> = {
      PENDING: 'warning',
      CONFIRMED: 'info',
      ACTIVE: 'success',
      COMPLETED: 'success',
      CANCELLED_BY_TENANT: 'error',
      CANCELLED_BY_LANDLORD: 'error',
      REJECTED: 'error',
      EXPIRED: 'default',
    };
    return <Badge variant={map[status] || 'default'} size="sm">{status.replace(/_/g, ' ')}</Badge>;
  };

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

      <div className="flex gap-2 mb-4 flex-wrap">
        {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-violet-100 text-violet-700' : 'text-gray-500 hover:bg-gray-100'
            }`}
          >
            {t}
          </button>
        ))}
      </div>

      <DataTable
        columns={[
          {
            key: 'listing',
            header: 'Listing',
            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" alt="" />
                  ) : (
                    <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 className="flex items-center gap-2">
                {b.tenant.avatar ? (
                  <img src={b.tenant.avatar} className="w-6 h-6 rounded-full object-cover" alt="" />
                ) : (
                  <div className="w-6 h-6 rounded-full bg-violet-100 flex items-center justify-center text-xs font-medium text-violet-700">
                    {b.tenant.fullName.charAt(0)}
                  </div>
                )}
                <span className="text-sm">{b.tenant.fullName}</span>
              </div>
            ),
          },
          {
            key: 'dates',
            header: 'Dates',
            render: (b: Booking) => (
              <div className="text-sm">
                <div>{new Date(b.startDate).toLocaleDateString()}</div>
                <div className="text-gray-400">to {new Date(b.endDate).toLocaleDateString()}</div>
              </div>
            ),
          },
          {
            key: 'amount',
            header: 'Amount',
            render: (b: Booking) => <span className="font-medium">${b.totalAmount.toFixed(2)}</span>,
          },
          {
            key: 'status',
            header: 'Status',
            render: (b: Booking) => statusBadge(b.status),
          },
        ]}
        data={bookings}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        actions={(b: Booking) => (
          <div className="flex items-center gap-1 justify-end">
            {b.status === 'PENDING' && (
              <>
                <button
                  onClick={() => handleAction(b.id, 'confirm')}
                  className="p-1.5 rounded-lg hover:bg-green-50 text-gray-500 hover:text-green-600 cursor-pointer"
                  title="Confirm"
                >
                  <Check className="w-4 h-4" />
                </button>
                <button
                  onClick={() => handleAction(b.id, 'reject')}
                  className="p-1.5 rounded-lg hover:bg-red-50 text-gray-500 hover:text-red-600 cursor-pointer"
                  title="Reject"
                >
                  <X className="w-4 h-4" />
                </button>
              </>
            )}
            {(b.status === 'CONFIRMED' || b.status === 'ACTIVE') && (
              <button
                onClick={() => handleAction(b.id, 'complete')}
                className="p-1.5 rounded-lg hover:bg-green-50 text-gray-500 hover:text-green-600 cursor-pointer"
                title="Complete"
              >
                <CheckCircle className="w-4 h-4" />
              </button>
            )}
          </div>
        )}
      />
    </div>
  );
}
