import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { Pencil, Pause, Play, Trash2 } from 'lucide-react';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { api } from '../../api/client';
import type { RentalListing } from '../../types/rental';

export function LandlordListingsPage() {
  const [listings, setListings] = useState<RentalListing[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');

  const fetchListings = useCallback(async () => {
    try {
      const params = new URLSearchParams({ page: String(page), pageSize: '20' });
      if (search) params.set('search', search);
      const res = await api.get<RentalListing[]>(`/rentals/mine?${params}`);
      setListings(res);
      setTotal(res.length);
    } catch {
      // silently fail
    }
  }, [page, search]);

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

  const handleToggleStatus = async (listing: RentalListing) => {
    try {
      if (listing.status === 'ACTIVE') {
        await api.post(`/rentals/${listing.id}/pause`);
      } else {
        await api.post(`/rentals/${listing.id}/activate`);
      }
      fetchListings();
    } catch {
      // silently fail
    }
  };

  const handleDelete = async (listing: RentalListing) => {
    if (!window.confirm(`Delete "${listing.title}"? This cannot be undone.`)) return;
    try {
      await api.delete(`/rentals/${listing.id}`);
      fetchListings();
    } catch {
      // silently fail
    }
  };

  const statusBadge = (status: string) => {
    const map: Record<string, 'success' | 'warning' | 'info' | 'error' | 'default'> = {
      ACTIVE: 'success',
      PAUSED: 'warning',
      PENDING_REVIEW: 'info',
      DRAFT: 'default',
      DELETED: 'error',
    };
    return <Badge variant={map[status] || 'default'} size="sm">{status.replace(/_/g, ' ')}</Badge>;
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-2xl font-bold text-gray-900">My Rentals</h1>
        <Link to="/rentals/new">
          <Button variant="primary" size="sm">+ New Rental</Button>
        </Link>
      </div>

      <DataTable
        columns={[
          {
            key: 'title',
            header: 'Listing',
            render: (l: RentalListing) => (
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-gray-100 overflow-hidden flex-shrink-0">
                  {l.images[0] ? (
                    <img src={l.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">{l.title}</p>
                  <p className="text-xs text-gray-400">{l.location}</p>
                </div>
              </div>
            ),
          },
          {
            key: 'category',
            header: 'Category',
            render: (l: RentalListing) => l.category.replace(/_/g, ' '),
          },
          {
            key: 'status',
            header: 'Status',
            render: (l: RentalListing) => statusBadge(l.status),
          },
          {
            key: 'price',
            header: 'Price',
            render: (l: RentalListing) => (
              <div className="text-sm">
                {l.dailyPrice != null && <div>${l.dailyPrice}/day</div>}
                {l.monthlyPrice != null && <div>${l.monthlyPrice}/mo</div>}
              </div>
            ),
          },
          {
            key: 'bookings',
            header: 'Bookings',
            render: (l: RentalListing) => l._count?.bookings ?? 0,
          },
        ]}
        data={listings}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        searchValue={search}
        onSearch={(v) => { setSearch(v); setPage(1); }}
        searchPlaceholder="Search rentals..."
        actions={(l: RentalListing) => (
          <div className="flex items-center gap-1 justify-end">
            <Link to={`/rentals/${l.id}/edit`}>
              <button className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-500 hover:text-gray-700 cursor-pointer" title="Edit">
                <Pencil className="w-4 h-4" />
              </button>
            </Link>
            <button
              onClick={() => handleToggleStatus(l)}
              className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-500 hover:text-gray-700 cursor-pointer"
              title={l.status === 'ACTIVE' ? 'Pause' : 'Activate'}
            >
              {l.status === 'ACTIVE' ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
            </button>
            <button
              onClick={() => handleDelete(l)}
              className="p-1.5 rounded-lg hover:bg-red-50 text-gray-500 hover:text-red-600 cursor-pointer"
              title="Delete"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </div>
        )}
      />
    </div>
  );
}
