import { useState, useEffect, useCallback } from 'react';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { Modal } from '../../components/ui/Modal';
import { api } from '../../api/client';
import { formatCurrency } from '../../utils/format';
import type { RentalListing, RentalListingStatus, RentalCategory } from '../../types/rental';

const STATUS_TABS: (RentalListingStatus | 'ALL')[] = ['ALL', 'PENDING_REVIEW', 'ACTIVE', 'PAUSED', 'DELETED'];
const CATEGORY_OPTIONS: (RentalCategory | 'ALL')[] = ['ALL', 'APARTMENT', 'HOUSE', 'CAR', 'MOTORCYCLE', 'BICYCLE', 'EBIKE'];

export function AdminRentalsPage() {
  const [rentals, setRentals] = useState<RentalListing[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusTab, setStatusTab] = useState<RentalListingStatus | 'ALL'>('ALL');
  const [categoryFilter, setCategoryFilter] = useState<RentalCategory | 'ALL'>('ALL');

  // Rejection modal
  const [showReject, setShowReject] = useState(false);
  const [rejectId, setRejectId] = useState('');
  const [rejectReason, setRejectReason] = useState('');

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

    try {
      const res = await api.get<{ data: RentalListing[]; total: number }>(`/admin/rentals?${params}`);
      setRentals(res.data);
      setTotal(res.total);
    } catch {
      setRentals([]);
    }
  }, [page, search, statusTab, categoryFilter]);

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

  const handleApprove = async (id: string) => {
    try {
      await api.patch(`/admin/rentals/${id}/approve`);
      fetchRentals();
    } catch {}
  };

  const openReject = (id: string) => {
    setRejectId(id);
    setRejectReason('');
    setShowReject(true);
  };

  const handleReject = async () => {
    try {
      await api.patch(`/admin/rentals/${rejectId}/reject`, { reason: rejectReason });
      setShowReject(false);
      fetchRentals();
    } catch {}
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this rental?')) return;
    try {
      await api.delete(`/admin/rentals/${id}`);
      fetchRentals();
    } catch {}
  };

  const statusBadge = (status: string) => {
    const v = status === 'ACTIVE' ? 'success' : status === 'PENDING_REVIEW' ? 'warning' : status === 'PAUSED' ? 'info' : 'error';
    return <Badge variant={v} size="sm">{status.replace(/_/g, ' ')}</Badge>;
  };

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

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

      {/* Category filter */}
      <div className="flex items-center gap-3 mb-4">
        <span className="text-sm text-gray-500">Category:</span>
        <select
          value={categoryFilter}
          onChange={(e) => { setCategoryFilter(e.target.value as RentalCategory | 'ALL'); setPage(1); }}
          className="rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm focus:border-primary-400 focus:outline-none"
        >
          {CATEGORY_OPTIONS.map(c => (
            <option key={c} value={c}>{c.replace(/_/g, ' ')}</option>
          ))}
        </select>
      </div>

      <DataTable
        columns={[
          {
            key: 'title',
            header: 'Rental',
            render: (r: RentalListing) => (
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-gray-100 overflow-hidden flex-shrink-0">
                  {r.images[0] ? <img src={r.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">{r.title}</p>
                  <p className="text-xs text-gray-400">{r.landlord.fullName}</p>
                </div>
              </div>
            ),
          },
          { key: 'category', header: 'Category', render: (r: RentalListing) => r.category.replace(/_/g, ' ') },
          {
            key: 'price',
            header: 'Price',
            render: (r: RentalListing) => (
              <div className="text-sm">
                {r.dailyPrice != null && <p>{formatCurrency(r.dailyPrice)}/day</p>}
                {r.monthlyPrice != null && <p>{formatCurrency(r.monthlyPrice)}/mo</p>}
              </div>
            ),
          },
          { key: 'status', header: 'Status', render: (r: RentalListing) => statusBadge(r.status) },
          { key: 'views', header: 'Views', render: (r: RentalListing) => r.viewCount },
          { key: 'createdAt', header: 'Created', render: (r: RentalListing) => new Date(r.createdAt).toLocaleDateString() },
        ]}
        data={rentals}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        searchValue={search}
        onSearch={(v) => { setSearch(v); setPage(1); }}
        searchPlaceholder="Search rentals..."
        actions={(r: RentalListing) => (
          <div className="flex items-center gap-1">
            {r.status === 'PENDING_REVIEW' && (
              <>
                <Button variant="secondary" size="sm" onClick={() => handleApprove(r.id)}>Approve</Button>
                <Button variant="secondary" size="sm" onClick={() => openReject(r.id)}>Reject</Button>
              </>
            )}
            <Button variant="secondary" size="sm" onClick={() => handleDelete(r.id)}>Delete</Button>
          </div>
        )}
      />

      {/* Rejection reason modal */}
      <Modal isOpen={showReject} onClose={() => setShowReject(false)} title="Reject Rental" size="sm">
        <div className="mb-6">
          <label className="block text-sm font-medium text-gray-700 mb-1.5">Reason for rejection</label>
          <textarea
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
            rows={3}
            placeholder="Provide a reason..."
            className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none"
          />
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowReject(false)}>Cancel</Button>
          <Button variant="danger" className="flex-1" onClick={handleReject}>Reject</Button>
        </div>
      </Modal>
    </div>
  );
}
