import { useState, useEffect } from 'react';
import { Star, Send } from 'lucide-react';
import { Badge } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { useAuth } from '../../context/AuthContext';
import { api } from '../../api/client';
import type { RentalReview } from '../../types/rental';

function StarRating({ rating }: { rating: number }) {
  return (
    <div className="flex items-center gap-0.5">
      {Array.from({ length: 5 }).map((_, i) => (
        <Star
          key={i}
          className={`w-4 h-4 ${i < rating ? 'fill-yellow-400 text-yellow-400' : 'text-gray-200'}`}
        />
      ))}
    </div>
  );
}

function ReviewCard({
  review,
  onRespond,
}: {
  review: RentalReview;
  onRespond: (reviewId: string, response: string) => Promise<void>;
}) {
  const [responding, setResponding] = useState(false);
  const [response, setResponse] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!response.trim()) return;
    setSubmitting(true);
    try {
      await onRespond(review.id, response.trim());
      setResponding(false);
      setResponse('');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-5">
      <div className="flex items-start justify-between gap-4 mb-3">
        <div className="flex items-center gap-3">
          {review.tenant?.avatar ? (
            <img src={review.tenant.avatar} className="w-10 h-10 rounded-full object-cover" alt="" />
          ) : (
            <div className="w-10 h-10 rounded-full bg-violet-100 flex items-center justify-center text-sm font-medium text-violet-700">
              {review.tenant?.fullName?.charAt(0) || '?'}
            </div>
          )}
          <div>
            <p className="font-medium text-gray-900">{review.tenant?.fullName || 'Unknown'}</p>
            <p className="text-xs text-gray-400">{new Date(review.createdAt).toLocaleDateString()}</p>
          </div>
        </div>
        <StarRating rating={review.rating} />
      </div>

      {review.rentalListing && (
        <div className="mb-2">
          <Badge variant="info" size="sm">{review.rentalListing.title}</Badge>
        </div>
      )}

      {review.comment && (
        <p className="text-sm text-gray-700 mb-3">{review.comment}</p>
      )}

      {review.landlordResponse ? (
        <div className="bg-violet-50 rounded-xl p-3 mt-3">
          <p className="text-xs font-medium text-violet-700 mb-1">Your Response</p>
          <p className="text-sm text-violet-900">{review.landlordResponse}</p>
        </div>
      ) : (
        <div className="mt-3">
          {responding ? (
            <div className="space-y-2">
              <textarea
                value={response}
                onChange={(e) => setResponse(e.target.value)}
                placeholder="Write your response..."
                rows={3}
                className="w-full px-3 py-2 rounded-xl border border-gray-200 text-sm focus:border-violet-400 focus:ring-2 focus:ring-violet-100 focus:outline-none resize-none"
              />
              <div className="flex items-center gap-2">
                <Button variant="primary" size="sm" onClick={handleSubmit} isLoading={submitting}>
                  <Send className="w-3.5 h-3.5 mr-1.5" />
                  Submit
                </Button>
                <Button variant="ghost" size="sm" onClick={() => { setResponding(false); setResponse(''); }}>
                  Cancel
                </Button>
              </div>
            </div>
          ) : (
            <button
              onClick={() => setResponding(true)}
              className="text-sm text-violet-600 hover:text-violet-700 font-medium cursor-pointer"
            >
              Respond to review
            </button>
          )}
        </div>
      )}
    </div>
  );
}

export function LandlordReviewsPage() {
  const { user } = useAuth();
  const [reviews, setReviews] = useState<RentalReview[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user) return;
    api
      .get<{ reviews: RentalReview[]; avgRating: number; totalReviews: number }>(`/rental-reviews/landlord/${user.id}`)
      .then(res => setReviews(res.reviews))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [user]);

  const handleRespond = async (reviewId: string, response: string) => {
    await api.patch(`/rental-reviews/${reviewId}/respond`, { response });
    setReviews((prev) =>
      prev.map((r) => (r.id === reviewId ? { ...r, landlordResponse: response } : r))
    );
  };

  const avgRating =
    reviews.length > 0
      ? reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length
      : 0;

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Reviews</h1>
        <div className="flex items-center gap-2 text-sm text-gray-500">
          <StarRating rating={Math.round(avgRating)} />
          <span className="font-medium text-gray-900">{avgRating.toFixed(1)}</span>
          <span>({reviews.length} review{reviews.length !== 1 ? 's' : ''})</span>
        </div>
      </div>

      {reviews.length === 0 ? (
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-12 text-center">
          <Star className="w-12 h-12 text-gray-200 mx-auto mb-3" />
          <p className="text-gray-500">No reviews yet</p>
          <p className="text-sm text-gray-400 mt-1">Reviews from tenants will appear here</p>
        </div>
      ) : (
        <div className="space-y-4">
          {reviews.map((review) => (
            <ReviewCard key={review.id} review={review} onRespond={handleRespond} />
          ))}
        </div>
      )}
    </div>
  );
}
