'use client'

import { useEffect, useState } from 'react'
import { Star, MessageSquare, AlertTriangle } from 'lucide-react'
import { apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'

// ─── i18n ─────────────────────────────────────────────────────────────────────

const copy = {
  en: {
    heading: 'Reviews',
    subtitle: 'Customer feedback for your company',
    totalReviews: 'Total Reviews',
    avgRating: 'Average Rating',
    fiveStars: '5-Star Reviews',
    negative: 'Negative Reviews',
    filterRating: 'Filter by rating',
    allRatings: 'All ratings',
    filterDate: 'Date range',
    last7: 'Last 7 days',
    last30: 'Last 30 days',
    last90: 'Last 90 days',
    allTime: 'All time',
    customer: 'Customer',
    vehicle: 'Vehicle',
    date: 'Date',
    rating: 'Rating',
    comment: 'Comment',
    reply: 'Reply',
    replied: 'Replied',
    noReply: 'No reply yet',
    saveReply: 'Save reply',
    cancel: 'Cancel',
    saving: 'Saving…',
    noReviews: 'No reviews yet',
    newComplaint: 'New complaint',
    replyPlaceholder: 'Write your reply…',
    errorLoad: 'Failed to load reviews',
    errorReply: 'Failed to save reply',
    stars: (n: number) => n === 1 ? '1 star' : `${n} stars`,
  },
  fr: {
    heading: 'Avis',
    subtitle: 'Retours clients pour votre entreprise',
    totalReviews: 'Total des avis',
    avgRating: 'Note moyenne',
    fiveStars: 'Avis 5 étoiles',
    negative: 'Avis négatifs',
    filterRating: 'Filtrer par note',
    allRatings: 'Toutes les notes',
    filterDate: 'Période',
    last7: '7 derniers jours',
    last30: '30 derniers jours',
    last90: '90 derniers jours',
    allTime: 'Tout le temps',
    customer: 'Client',
    vehicle: 'Véhicule',
    date: 'Date',
    rating: 'Note',
    comment: 'Commentaire',
    reply: 'Répondre',
    replied: 'Répondu',
    noReply: 'Pas encore de réponse',
    saveReply: 'Enregistrer',
    cancel: 'Annuler',
    saving: 'Enregistrement…',
    noReviews: 'Aucun avis pour l\'instant',
    newComplaint: 'Nouvelle plainte',
    replyPlaceholder: 'Rédigez votre réponse…',
    errorLoad: 'Échec du chargement des avis',
    errorReply: 'Échec de l\'enregistrement de la réponse',
    stars: (n: number) => n === 1 ? '1 étoile' : `${n} étoiles`,
  },
  ar: {
    heading: 'التقييمات',
    subtitle: 'آراء العملاء لشركتك',
    totalReviews: 'إجمالي التقييمات',
    avgRating: 'متوسط التقييم',
    fiveStars: 'تقييمات 5 نجوم',
    negative: 'تقييمات سلبية',
    filterRating: 'تصفية حسب التقييم',
    allRatings: 'جميع التقييمات',
    filterDate: 'النطاق الزمني',
    last7: 'آخر 7 أيام',
    last30: 'آخر 30 يوماً',
    last90: 'آخر 90 يوماً',
    allTime: 'كل الوقت',
    customer: 'العميل',
    vehicle: 'المركبة',
    date: 'التاريخ',
    rating: 'التقييم',
    comment: 'تعليق',
    reply: 'رد',
    replied: 'تم الرد',
    noReply: 'لم يتم الرد بعد',
    saveReply: 'حفظ الرد',
    cancel: 'إلغاء',
    saving: 'جار الحفظ…',
    noReviews: 'لا توجد تقييمات بعد',
    newComplaint: 'شكوى جديدة',
    replyPlaceholder: 'اكتب ردك هنا…',
    errorLoad: 'فشل تحميل التقييمات',
    errorReply: 'فشل حفظ الرد',
    stars: (n: number) => `${n} نجوم`,
  },
} as const

// ─── Types ─────────────────────────────────────────────────────────────────────

interface ReviewReservation {
  id: string
  startDate: string
  endDate: string
  customer: { id: string; firstName: string; lastName: string; email: string }
  vehicle: { make: string; model: string; year: number }
}

interface Review {
  id: string
  reservationId: string
  overallRating: number
  vehicleRating: number | null
  serviceRating: number | null
  comment: string | null
  companyReply: string | null
  companyRepliedAt: string | null
  isPublished: boolean
  createdAt: string
  reservation: ReviewReservation
}

interface ReviewsResponse {
  data: Review[]
  meta: { total: number; page: number; pageSize: number; totalPages: number }
}

interface Stats {
  total: number
  averageOverall: number
  averageVehicle: number
  averageService: number
  byRating: Record<string, number>
}

// ─── Star display ──────────────────────────────────────────────────────────────

function StarDisplay({ rating, size = 'sm' }: { rating: number; size?: 'sm' | 'md' }) {
  const sz = size === 'md' ? 'h-5 w-5' : 'h-4 w-4'
  return (
    <div className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map((s) => (
        <Star
          key={s}
          className={`${sz} ${s <= rating ? 'fill-amber-400 text-amber-400' : 'text-stone-300 dark:text-blue-900'}`}
        />
      ))}
    </div>
  )
}

// ─── Main page ─────────────────────────────────────────────────────────────────

export default function ReviewsPage() {
  const { language } = useDashboardI18n()
  const t = copy[language as keyof typeof copy] ?? copy.en

  const [reviews, setReviews] = useState<Review[]>([])
  const [meta, setMeta] = useState({ total: 0, page: 1, pageSize: 20, totalPages: 1 })
  const [stats, setStats] = useState<Stats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const [filterRating, setFilterRating] = useState<string>('')
  const [filterDays, setFilterDays] = useState<string>('')
  const [page, setPage] = useState(1)

  const [replyingId, setReplyingId] = useState<string | null>(null)
  const [replyText, setReplyText] = useState('')
  const [replySaving, setReplySaving] = useState(false)

  async function loadData() {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams({ page: String(page), pageSize: '20' })
      if (filterRating) params.set('rating', filterRating)

      const [reviewsData, statsData] = await Promise.all([
        apiFetch<ReviewsResponse>(`/reviews?${params}`),
        apiFetch<Stats>('/reviews/stats'),
      ])

      let data = reviewsData.data ?? []
      if (filterDays) {
        const cutoff = new Date()
        cutoff.setDate(cutoff.getDate() - Number(filterDays))
        data = data.filter((r) => new Date(r.createdAt) >= cutoff)
      }

      setReviews(data)
      setMeta(reviewsData.meta ?? { total: 0, page: 1, pageSize: 20, totalPages: 1 })
      setStats(statsData)
    } catch {
      setError(t.errorLoad)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { loadData() }, [page, filterRating, filterDays])

  async function handleSaveReply(reviewId: string) {
    if (!replyText.trim()) return
    setReplySaving(true)
    try {
      await apiFetch(`/reviews/${reviewId}/reply`, {
        method: 'PATCH',
        body: JSON.stringify({ companyReply: replyText.trim() }),
      })
      setReplyingId(null)
      setReplyText('')
      await loadData()
    } catch {
      alert(t.errorReply)
    } finally {
      setReplySaving(false)
    }
  }

  function startReply(review: Review) {
    setReplyingId(review.id)
    setReplyText(review.companyReply ?? '')
  }

  const isRtl = language === 'ar'

  return (
    <div className={`space-y-6 p-6 ${isRtl ? 'rtl' : 'ltr'}`}>
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-blue-950 dark:text-white">{t.heading}</h1>
        <p className="mt-1 text-sm text-stone-500 dark:text-slate-400">{t.subtitle}</p>
      </div>

      {/* Stats cards */}
      {stats && (
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
          <div className="card p-5">
            <p className="text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.totalReviews}</p>
            <p className="mt-2 text-3xl font-bold text-blue-950 dark:text-white">{stats.total}</p>
          </div>
          <div className="card p-5">
            <p className="text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.avgRating}</p>
            <div className="mt-2 flex items-center gap-2">
              <p className="text-3xl font-bold text-blue-950 dark:text-white">{stats.averageOverall.toFixed(1)}</p>
              <StarDisplay rating={Math.round(stats.averageOverall)} size="md" />
            </div>
          </div>
          <div className="card p-5">
            <p className="text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.fiveStars}</p>
            <p className="mt-2 text-3xl font-bold text-emerald-600 dark:text-emerald-400">{stats.byRating['5'] ?? 0}</p>
          </div>
          <div className="card p-5">
            <p className="text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.negative}</p>
            <p className="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">
              {(stats.byRating['1'] ?? 0) + (stats.byRating['2'] ?? 0)}
            </p>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="card p-4">
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium text-stone-700 dark:text-slate-300">{t.filterRating}</label>
            <select
              value={filterRating}
              onChange={(e) => { setFilterRating(e.target.value); setPage(1) }}
              className="input-field w-auto"
            >
              <option value="">{t.allRatings}</option>
              {[5, 4, 3, 2, 1].map((r) => (
                <option key={r} value={String(r)}>{t.stars(r)}</option>
              ))}
            </select>
          </div>
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium text-stone-700 dark:text-slate-300">{t.filterDate}</label>
            <select
              value={filterDays}
              onChange={(e) => { setFilterDays(e.target.value); setPage(1) }}
              className="input-field w-auto"
            >
              <option value="">{t.allTime}</option>
              <option value="7">{t.last7}</option>
              <option value="30">{t.last30}</option>
              <option value="90">{t.last90}</option>
            </select>
          </div>
        </div>
      </div>

      {/* Reviews list */}
      {loading ? (
        <div className="card p-10 text-center text-stone-400 dark:text-slate-500">Loading…</div>
      ) : error ? (
        <div className="card p-10 text-center text-red-500">{error}</div>
      ) : reviews.length === 0 ? (
        <div className="card p-10 text-center text-stone-400 dark:text-slate-500">{t.noReviews}</div>
      ) : (
        <div className="space-y-4">
          {reviews.map((review) => {
            const customer = review.reservation?.customer
            const vehicle = review.reservation?.vehicle
            const vehicleLabel = vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model}` : '—'
            const customerName = customer ? `${customer.firstName} ${customer.lastName}` : '—'
            const isReplying = replyingId === review.id
            const isNegative = review.overallRating <= 2

            return (
              <div key={review.id} className={`card p-5 ${isNegative ? 'border-red-200 dark:border-red-900/40' : ''}`}>
                <div className="flex flex-wrap items-start justify-between gap-4">
                  <div className="flex-1 space-y-1">
                    <div className="flex flex-wrap items-center gap-3">
                      <span className="font-semibold text-blue-950 dark:text-white">{customerName}</span>
                      <span className="text-sm text-stone-400 dark:text-slate-500">{vehicleLabel}</span>
                      <span className="text-xs text-stone-400 dark:text-slate-500">
                        {new Date(review.createdAt).toLocaleDateString()}
                      </span>
                    </div>
                    <StarDisplay rating={review.overallRating} />
                    {review.comment && (
                      <p className="mt-2 line-clamp-3 text-sm text-stone-600 dark:text-slate-300">{review.comment}</p>
                    )}
                    {review.companyReply && !isReplying && (
                      <div className="mt-3 rounded-2xl border border-blue-100 bg-blue-50 p-3 dark:border-blue-900/40 dark:bg-blue-950/30">
                        <div className="mb-1 flex items-center gap-2">
                          <MessageSquare className="h-3.5 w-3.5 text-blue-500" />
                          <span className="text-xs font-medium text-blue-600 dark:text-blue-400">{t.replied}</span>
                        </div>
                        <p className="text-sm text-stone-600 dark:text-slate-300">{review.companyReply}</p>
                      </div>
                    )}
                  </div>
                  <div className="flex shrink-0 flex-wrap gap-2">
                    <button
                      onClick={() => startReply(review)}
                      className="btn-secondary text-xs"
                    >
                      <MessageSquare className="h-3.5 w-3.5" />
                      {review.companyReply ? t.replied : t.reply}
                    </button>
                    <a
                      href={`/complaints?reservationId=${review.reservation?.id ?? ''}`}
                      className="btn-secondary text-xs"
                    >
                      <AlertTriangle className="h-3.5 w-3.5" />
                      {t.newComplaint}
                    </a>
                  </div>
                </div>

                {/* Inline reply form */}
                {isReplying && (
                  <div className="mt-4 space-y-3">
                    <textarea
                      value={replyText}
                      onChange={(e) => setReplyText(e.target.value)}
                      placeholder={t.replyPlaceholder}
                      rows={3}
                      className="input-field resize-none"
                    />
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleSaveReply(review.id)}
                        disabled={replySaving || !replyText.trim()}
                        className="btn-primary text-sm"
                      >
                        {replySaving ? t.saving : t.saveReply}
                      </button>
                      <button
                        onClick={() => { setReplyingId(null); setReplyText('') }}
                        className="btn-secondary text-sm"
                      >
                        {t.cancel}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}

      {/* Pagination */}
      {meta.totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="btn-secondary text-sm"
          >
            ←
          </button>
          <span className="text-sm text-stone-600 dark:text-slate-400">
            {page} / {meta.totalPages}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(meta.totalPages, p + 1))}
            disabled={page >= meta.totalPages}
            className="btn-secondary text-sm"
          >
            →
          </button>
        </div>
      )}
    </div>
  )
}
