import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { DataTable } from '../components/ui/DataTable';
import { Button } from '../components/ui/Button';
import { GradientButton } from '../components/ui/GradientButton';
import { Modal } from '../components/ui/Modal';
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'];

export function MyBookingsPage() {
  const navigate = useNavigate();
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [tab, setTab] = useState<BookingStatus | 'ALL'>('ALL');
  const [, setLoading] = useState(true);

  // Review modal
  const [showReview, setShowReview] = useState(false);
  const [reviewBookingId, setReviewBookingId] = useState('');
  const [reviewRating, setReviewRating] = useState(5);
  const [reviewComment, setReviewComment] = useState('');
  const [reviewSubmitting, setReviewSubmitting] = useState(false);

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

    try {
      const res = await api.get<Booking[]>(`/bookings?${params}`);
      setBookings(res);
      setTotal(res.length);
    } catch {
      setBookings([]);
    } finally {
      setLoading(false);
    }
  }, [page, tab]);

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

  const handleCancel = async (bookingId: string) => {
    const reason = window.prompt('Reason for cancellation:');
    if (!reason) return;
    try {
      await api.patch(`/bookings/${bookingId}/cancel`, { reason });
      fetchBookings();
    } catch {}
  };

  const handlePay = async (bookingId: string) => {
    try {
      await api.post<{ clientSecret: string }>('/rental-payments/create-intent', { bookingId });
      alert('Payment intent created. In production, Stripe checkout would open here.');
      fetchBookings();
    } catch {}
  };

  const openReview = (bookingId: string) => {
    setReviewBookingId(bookingId);
    setReviewRating(5);
    setReviewComment('');
    setShowReview(true);
  };

  const handleSubmitReview = async () => {
    setReviewSubmitting(true);
    try {
      await api.post('/rental-reviews', {
        bookingId: reviewBookingId,
        rating: reviewRating,
        comment: reviewComment || undefined,
      });
      setShowReview(false);
      fetchBookings();
    } catch {} finally {
      setReviewSubmitting(false);
    }
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-4">My 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: '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 text-primary-600">{formatCurrency(b.totalAmount)}</span>,
          },
          {
            key: 'status',
            header: 'Status',
            render: (b: Booking) => <BookingStatusBadge status={b.status} />,
          },
        ]}
        data={bookings}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        actions={(b: Booking) => (
          <div className="flex items-center gap-1">
            <Button variant="secondary" size="sm" onClick={() => navigate(`/rentals/${b.rentalListingId}`)}>
              View
            </Button>
            {b.status === 'PENDING' && (
              <Button variant="secondary" size="sm" onClick={() => handleCancel(b.id)}>
                Cancel
              </Button>
            )}
            {b.status === 'CONFIRMED' && (
              <GradientButton size="sm" onClick={() => handlePay(b.id)}>
                Pay
              </GradientButton>
            )}
            {b.status === 'COMPLETED' && !b.review && (
              <Button variant="secondary" size="sm" onClick={() => openReview(b.id)}>
                Review
              </Button>
            )}
          </div>
        )}
      />

      {/* Review Modal */}
      <Modal isOpen={showReview} onClose={() => setShowReview(false)} title="Leave a Review" size="sm">
        <div className="space-y-4 mb-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1.5">Rating</label>
            <div className="flex gap-1">
              {[1, 2, 3, 4, 5].map(star => (
                <button
                  key={star}
                  type="button"
                  onClick={() => setReviewRating(star)}
                  className={`text-2xl cursor-pointer ${star <= reviewRating ? 'text-yellow-400' : 'text-gray-200'}`}
                >
                  {'\u2605'}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1.5">Comment (optional)</label>
            <textarea
              value={reviewComment}
              onChange={(e) => setReviewComment(e.target.value)}
              rows={3}
              placeholder="Share your experience..."
              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>
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowReview(false)}>Cancel</Button>
          <GradientButton className="flex-1" onClick={handleSubmitReview} disabled={reviewSubmitting}>
            {reviewSubmitting ? 'Submitting...' : 'Submit Review'}
          </GradientButton>
        </div>
      </Modal>
    </div>
  );
}
