"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Send,
  Mail,
  MessageSquare,
  Phone,
  Clock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
  ChevronDown,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Sent Review Requests",
    noRequests: "No review requests sent yet.",
    loadMore: "Load More",
    loadError: "Failed to load review requests",
    status: {
      PENDING: "Pending",
      SENT: "Sent",
      COMPLETED: "Completed",
      EXPIRED: "Expired",
    },
    channel: {
      whatsapp: "WhatsApp",
      email: "Email",
      sms: "SMS",
    },
    sentAt: "Sent",
    createdAt: "Created",
    expires: "Expires",
  },
  ar: {
    title: "طلبات التقييم المرسلة",
    noRequests: "لم يتم إرسال طلبات تقييم بعد.",
    loadMore: "تحميل المزيد",
    loadError: "فشل في تحميل طلبات التقييم",
    status: {
      PENDING: "قيد الانتظار",
      SENT: "تم الإرسال",
      COMPLETED: "مكتمل",
      EXPIRED: "منتهي",
    },
    channel: {
      whatsapp: "واتساب",
      email: "البريد الإلكتروني",
      sms: "رسالة نصية",
    },
    sentAt: "تم الإرسال",
    createdAt: "تاريخ الإنشاء",
    expires: "ينتهي",
  },
};

interface ReviewRequest {
  id: string;
  customerName: string;
  customerEmail: string | null;
  customerPhone: string | null;
  channel: string;
  status: string;
  sentAt: string | null;
  createdAt: string;
  expiresAt: string;
  source: string;
}

interface ReviewRequestsListProps {
  lang: string;
  refreshTrigger?: number;
}

const statusConfig: Record<
  string,
  { icon: typeof Clock; color: string; bg: string }
> = {
  PENDING: { icon: Clock, color: "text-amber-600", bg: "bg-amber-50" },
  SENT: { icon: Send, color: "text-blue-600", bg: "bg-blue-50" },
  COMPLETED: {
    icon: CheckCircle2,
    color: "text-green-600",
    bg: "bg-green-50",
  },
  EXPIRED: { icon: XCircle, color: "text-slate-400", bg: "bg-slate-50" },
};

const channelIcons: Record<string, typeof Mail> = {
  email: Mail,
  whatsapp: MessageSquare,
  sms: Phone,
};

export default function ReviewRequestsList({
  lang,
  refreshTrigger,
}: ReviewRequestsListProps) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [requests, setRequests] = useState<ReviewRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  const fetchRequests = useCallback(
    async (p = 1, append = false) => {
      try {
        setLoading(true);
        const res = await fetchWithCSRF(
          `/api/dashboard/reviews/requests?page=${p}&limit=20`,
        );
        if (res.ok) {
          const data = await res.json();
          if (append) {
            setRequests((prev) => [...prev, ...(data.requests ?? [])]);
          } else {
            setRequests(data.requests ?? []);
          }
          setTotal(data.total ?? 0);
          setPage(p);
        } else {
          setError(labels.loadError);
        }
      } catch {
        setError(labels.loadError);
      } finally {
        setLoading(false);
      }
    },
    [labels.loadError],
  );

  useEffect(() => {
    fetchRequests();
  }, [fetchRequests, refreshTrigger]);

  const formatDate = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleDateString(isAr ? "ar-QA" : "en-QA", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateStr;
    }
  };

  if (loading && requests.length === 0) {
    return (
      <div className="flex items-center justify-center py-8">
        <Loader2 className="w-5 h-5 animate-spin text-brand-green" />
      </div>
    );
  }

  return (
    <div dir={isAr ? "rtl" : "ltr"} className="space-y-3">
      <h3 className="text-sm font-semibold text-slate-700">{labels.title}</h3>

      {error && (
        <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">
          {error}
        </p>
      )}

      {requests.length === 0 && !loading && (
        <div className="text-center py-8 text-slate-400 text-sm">
          <AlertCircle className="w-8 h-8 mx-auto mb-2 text-slate-300" />
          {labels.noRequests}
        </div>
      )}

      {requests.length > 0 && (
        <div className="space-y-2">
          {requests.map((req) => {
            const statusCfg = statusConfig[req.status] ?? statusConfig.PENDING;
            const StatusIcon = statusCfg.icon;
            const ChannelIcon = channelIcons[req.channel] ?? Mail;
            const channelLabel =
              labels.channel[req.channel as keyof typeof labels.channel] ??
              req.channel;
            const statusLabel =
              labels.status[req.status as keyof typeof labels.status] ??
              req.status;

            return (
              <div
                key={req.id}
                className="flex items-center gap-3 bg-slate-50 rounded-lg p-3 border border-slate-200"
              >
                {/* Channel icon */}
                <div className="shrink-0 w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center">
                  <ChannelIcon className="w-4 h-4 text-slate-500" />
                </div>

                {/* Main info */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-0.5">
                    <span className="text-sm font-medium text-slate-900 truncate">
                      {req.customerName}
                    </span>
                    <span
                      className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${statusCfg.bg} ${statusCfg.color}`}
                    >
                      <StatusIcon className="w-3 h-3" />
                      {statusLabel}
                    </span>
                  </div>
                  <div className="flex items-center gap-3 text-xs text-slate-400">
                    <span>{channelLabel}</span>
                    {req.customerPhone && <span>{req.customerPhone}</span>}
                    {req.customerEmail && (
                      <span className="truncate">{req.customerEmail}</span>
                    )}
                  </div>
                </div>

                {/* Date */}
                <div className="shrink-0 text-xs text-slate-400 text-end">
                  {formatDate(req.sentAt ?? req.createdAt)}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {requests.length < total && (
        <button
          onClick={() => fetchRequests(page + 1, true)}
          disabled={loading}
          className="flex items-center gap-1 mx-auto px-4 py-2 text-sm text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg"
        >
          {loading ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            <ChevronDown className="w-4 h-4" />
          )}
          {labels.loadMore}
        </button>
      )}
    </div>
  );
}
