import { useState, useEffect } from 'react';
import { ShoppingBag, Calendar, DollarSign, Star } from 'lucide-react';
import { StatCard } from '../../components/ui/StatCard';
import { Badge } from '../../components/ui/Badge';
import { api } from '../../api/client';
import type { RentalListing, Booking } from '../../types/rental';

interface LandlordStats {
  totalRentals: number;
  activeBookings: number;
  revenue: number;
  avgRating: number;
}

export function LandlordDashboardPage() {
  const [stats, setStats] = useState<LandlordStats | null>(null);
  const [recentBookings, setRecentBookings] = useState<Booking[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      try {
        const [rentals, bookings] = await Promise.all([
          api.get<RentalListing[]>('/rentals/mine'),
          api.get<Booking[]>('/bookings?role=landlord'),
        ]);

        const totalRentals = rentals.length;
        const activeBookings = bookings.filter(
          (b) => b.status === 'CONFIRMED' || b.status === 'ACTIVE'
        ).length;
        const revenue = bookings
          .filter((b) => b.status === 'COMPLETED')
          .reduce((sum, b) => sum + b.totalAmount, 0);

        const ratings = rentals.filter((r) => r.avgRating).map((r) => r.avgRating!);
        const avgRating = ratings.length > 0 ? ratings.reduce((a, b) => a + b, 0) / ratings.length : 0;

        setStats({ totalRentals, activeBookings, revenue, avgRating });
        setRecentBookings(bookings.slice(0, 5));
      } catch {
        // silently fail
      } finally {
        setLoading(false);
      }
    }
    fetchData();
  }, []);

  if (loading) {
    return <div className="text-center text-gray-400 py-12">Loading dashboard...</div>;
  }

  const bookingStatusBadge = (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-6">Landlord Dashboard</h1>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard icon={ShoppingBag} label="Total Rentals" value={stats?.totalRentals ?? 0} color="blue" />
        <StatCard icon={Calendar} label="Active Bookings" value={stats?.activeBookings ?? 0} color="green" />
        <StatCard icon={DollarSign} label="Revenue" value={`$${(stats?.revenue ?? 0).toFixed(2)}`} color="pink" />
        <StatCard icon={Star} label="Avg Rating" value={stats?.avgRating ? stats.avgRating.toFixed(1) : 'N/A'} color="yellow" />
      </div>

      <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-5">
        <h3 className="font-semibold text-gray-900 mb-4">Recent Bookings</h3>
        {recentBookings.length === 0 ? (
          <p className="text-sm text-gray-400 py-4 text-center">No bookings yet</p>
        ) : (
          <div className="space-y-3">
            {recentBookings.map((booking) => (
              <div key={booking.id} className="flex items-center justify-between p-3 rounded-xl bg-gray-50">
                <div className="flex items-center gap-3 min-w-0">
                  <div className="w-10 h-10 rounded-lg bg-gray-200 overflow-hidden flex-shrink-0">
                    {booking.rentalListing.images[0] ? (
                      <img src={booking.rentalListing.images[0].url} className="w-full h-full object-cover" alt="" />
                    ) : (
                      <div className="w-full h-full bg-gray-300" />
                    )}
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">{booking.rentalListing.title}</p>
                    <p className="text-xs text-gray-500">
                      {booking.tenant.fullName} &middot; {new Date(booking.startDate).toLocaleDateString()} - {new Date(booking.endDate).toLocaleDateString()}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3 flex-shrink-0">
                  <span className="text-sm font-semibold text-gray-900">${booking.totalAmount.toFixed(2)}</span>
                  {bookingStatusBadge(booking.status)}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
