'use client';

import { useTranslation } from 'react-i18next';
import { motion } from 'framer-motion';
import { Star, User, Calendar, MessageSquare, ThumbsUp, Loader2 } from 'lucide-react';
import toast, { Toaster } from 'react-hot-toast';
import { getCustomerRatings } from '../utils/ratings';
import AuthService from '../services/AuthService';
import StarRating from '../components/ratings/StarRating';

const RATING_FIELDS = [
  { key: 'cleanRating', label: 'ratings.cleanliness' },
  { key: 'servicesRating', label: 'ratings.services' },
  { key: 'ownerBehaviorRating', label: 'ratings.ownerBehavior' },
  { key: 'experienceRating', label: 'ratings.experience' },
];

function calcOverall(ratings) {
  if (!ratings || ratings.length === 0) return 0;
  const total = ratings.reduce((sum, r) => {
    const avg = RATING_FIELDS.reduce((s, f) => s + (Number(r[f.key]) || 0), 0) / RATING_FIELDS.length;
    return sum + avg;
  }, 0);
  return total / ratings.length;
}

function RatingCard({ rating, t }) {
  const dateStr = rating.createdAt
    ? new Date(rating.createdAt).toLocaleDateString('ar')
    : null;

  return (
    <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}
      className="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-all">
      <div className="flex items-center gap-3 mb-4 pb-3 border-b border-gray-100">
        <div className="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center">
          <User className="w-5 h-5 text-amber-600" />
        </div>
        <div>
          <p className="font-medium text-gray-900">{rating.ownerName || 'مالك العقار'}</p>
          {dateStr && (
            <div className="flex items-center gap-1 text-xs text-gray-400">
              <Calendar className="w-3 h-3" /> {dateStr}
            </div>
          )}
        </div>
      </div>

      <div className="space-y-3 mb-4">
        {RATING_FIELDS.map(({ key, label }) => (
          <div key={key} className="flex items-center justify-between">
            <span className="text-sm text-gray-600">{t(label)}</span>
            <div className="flex items-center gap-2">
              <StarRating rating={Number(rating[key]) || 0} size={18} readOnly />
              <span className="text-sm font-medium text-gray-700 w-6 text-left">
                {Number(rating[key]) || 0}
              </span>
            </div>
          </div>
        ))}
      </div>

      {rating.comment && (
        <div className="bg-gray-50 rounded-xl p-3 flex items-start gap-2">
          <MessageSquare className="w-4 h-4 text-gray-400 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-gray-600">{rating.comment}</p>
        </div>
      )}
    </motion.div>
  );
}

export default function MyRatesPage() {
  const { t } = useTranslation();
  const [ratings, setRatings] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const user = AuthService.getUser();
    if (!user || !user.id) {
      toast.error(t('auth.loginRequired'));
      setLoading(false);
      return;
    }
    loadRatings(user.id);
  }, [t]);

  async function loadRatings(userId) {
    try {
      const data = await getCustomerRatings(userId);
      const list = Array.isArray(data) ? data : [];
      setRatings(list);
    } catch (err) {
      console.error(err);
      toast.error(t('ratings.loadError'));
      setRatings([]);
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center" dir="rtl">
        <Loader2 className="w-12 h-12 text-amber-500 animate-spin" />
      </div>
    );
  }

  const overall = calcOverall(ratings);

  return (
    <div className="min-h-screen bg-gray-50 py-8" dir="rtl">
      <Toaster position="top-center" reverseOrder={false} />
      <div className="container mx-auto px-4">
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">{t('ratings.myRatings')}</h1>
          <p className="text-gray-600">{t('ratings.receivedFromOwners')}</p>
        </motion.div>

        {ratings.length > 0 && (
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}
            className="bg-gradient-to-br from-amber-500 to-amber-600 rounded-2xl p-6 mb-8 text-white text-center shadow-lg">
            <ThumbsUp className="w-8 h-8 mx-auto mb-2 opacity-80" />
            <div className="flex items-center justify-center gap-2 mb-1">
              <StarRating rating={Math.round(overall)} size={24} readOnly />
            </div>
            <div className="text-4xl font-bold">{overall.toFixed(1)}</div>
            <div className="text-amber-100 text-sm mt-1">{t('ratings.overallAverage')}</div>
            <div className="text-amber-100 text-xs mt-2">
              {t('ratings.basedOn')} {ratings.length} {ratings.length === 1 ? t('ratings.review') : t('ratings.reviews')}
            </div>
          </motion.div>
        )}

        {ratings.length === 0 ? (
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}
            className="bg-white rounded-2xl p-12 text-center border-2 border-dashed border-gray-300">
            <Star className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-xl font-bold text-gray-900 mb-2">{t('ratings.noRatings')}</h3>
            <p className="text-gray-500">{t('ratings.noRatingsDescription')}</p>
          </motion.div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {ratings.map((r, i) => (
              <RatingCard key={r.id || i} rating={r} t={t} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
