"use client";

import { useState, useEffect, useCallback } from "react";
import {
  X,
  Send,
  Loader2,
  CheckSquare,
  Square,
  Mail,
  MessageSquare,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Bulk Review Request",
    selectAll: "Select All",
    deselectAll: "Deselect All",
    channel: "Send via",
    whatsapp: "WhatsApp",
    email: "Email",
    both: "Both",
    send: "Send {count} Requests",
    cancel: "Cancel",
    sending: "Sending...",
    success: "{count} review requests sent!",
    error: "Failed to send review requests",
    loadError: "Failed to load bookings",
    noBookings: "No recent completed bookings found.",
    customer: "Customer",
    service: "Service",
    date: "Date",
    loading: "Loading bookings...",
    selected: "{count} selected",
  },
  ar: {
    title: "طلب تقييم جماعي",
    selectAll: "تحديد الكل",
    deselectAll: "إلغاء تحديد الكل",
    channel: "إرسال عبر",
    whatsapp: "واتساب",
    email: "البريد الإلكتروني",
    both: "كلاهما",
    send: "إرسال {count} طلبات",
    cancel: "إلغاء",
    sending: "جاري الإرسال...",
    success: "تم إرسال {count} طلبات تقييم!",
    error: "فشل في إرسال طلبات التقييم",
    loadError: "فشل في تحميل الحجوزات",
    noBookings: "لم يتم العثور على حجوزات مكتملة حديثة.",
    customer: "العميل",
    service: "الخدمة",
    date: "التاريخ",
    loading: "جاري تحميل الحجوزات...",
    selected: "{count} محدد",
  },
};

interface Booking {
  id: string;
  customerName: string;
  customerPhone: string | null;
  customerEmail: string | null;
  serviceName: string;
  completedAt: string;
}

interface BulkReviewRequestModalProps {
  lang: string;
  onClose: () => void;
  onSuccess?: () => void;
}

export default function BulkReviewRequestModal({
  lang,
  onClose,
  onSuccess,
}: BulkReviewRequestModalProps) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [bookings, setBookings] = useState<Booking[]>([]);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [channel, setChannel] = useState<"whatsapp" | "email" | "both">(
    "whatsapp",
  );
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [successMsg, setSuccessMsg] = useState("");

  const fetchBookings = useCallback(async () => {
    try {
      const res = await fetchWithCSRF(
        "/api/dashboard/reviews/requests/eligible-bookings",
      );
      if (res.ok) {
        const data = await res.json();
        setBookings(data.bookings ?? []);
      } else {
        setError(labels.loadError);
      }
    } catch {
      setError(labels.loadError);
    } finally {
      setLoading(false);
    }
  }, [labels.loadError]);

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

  const toggleSelect = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const toggleAll = () => {
    if (selected.size === bookings.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(bookings.map((b) => b.id)));
    }
  };

  const handleSend = async () => {
    if (selected.size === 0) return;
    setSending(true);
    setError("");
    setSuccessMsg("");
    try {
      // Build requests array from selected bookings with customer details
      const requests = bookings
        .filter((b) => selected.has(b.id))
        .map((b) => ({
          customerName: b.customerName,
          customerEmail: b.customerEmail ?? undefined,
          customerPhone: b.customerPhone ?? undefined,
          channel,
          bookingId: b.id,
        }));

      const res = await fetchWithCSRF("/api/dashboard/reviews/requests/bulk", {
        method: "POST",
        body: JSON.stringify({
          requests,
          language: isAr ? "ar" : "en",
        }),
      });
      if (!res.ok) throw new Error("Failed");
      const count = selected.size;
      setSuccessMsg(labels.success.replace("{count}", String(count)));
      onSuccess?.();
      setTimeout(onClose, 2000);
    } catch {
      setError(labels.error);
    } finally {
      setSending(false);
    }
  };

  const channels = [
    { id: "whatsapp" as const, label: labels.whatsapp, icon: MessageSquare },
    { id: "email" as const, label: labels.email, icon: Mail },
    { id: "both" as const, label: labels.both, icon: Send },
  ];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div
        className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b shrink-0">
          <h3 className="text-lg font-semibold text-slate-900">
            {labels.title}
          </h3>
          <button
            onClick={onClose}
            className="p-1 hover:bg-slate-100 rounded-lg"
          >
            <X className="w-5 h-5 text-slate-500" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
              <span className="ms-2 text-slate-500">{labels.loading}</span>
            </div>
          ) : bookings.length === 0 ? (
            <div className="text-center py-8 text-slate-500">
              {labels.noBookings}
            </div>
          ) : (
            <>
              {/* Select All / Count */}
              <div className="flex items-center justify-between">
                <button
                  onClick={toggleAll}
                  className="text-sm text-brand-green hover:text-brand-green/80"
                >
                  {selected.size === bookings.length
                    ? labels.deselectAll
                    : labels.selectAll}
                </button>
                <span className="text-xs text-slate-500">
                  {labels.selected.replace("{count}", String(selected.size))}
                </span>
              </div>

              {/* Bookings Table */}
              <div className="space-y-1">
                {bookings.map((booking) => (
                  <button
                    key={booking.id}
                    type="button"
                    onClick={() => toggleSelect(booking.id)}
                    className={`w-full flex items-center gap-3 p-3 rounded-lg text-start transition-colors ${
                      selected.has(booking.id)
                        ? "bg-blue-50 border border-blue-300"
                        : "bg-slate-50 border border-slate-200 hover:border-slate-300"
                    }`}
                  >
                    {selected.has(booking.id) ? (
                      <CheckSquare className="w-5 h-5 text-brand-green shrink-0" />
                    ) : (
                      <Square className="w-5 h-5 text-slate-400 shrink-0" />
                    )}
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-slate-900">
                        {booking.customerName}
                      </p>
                      <p className="text-xs text-slate-500">
                        {booking.serviceName}
                      </p>
                    </div>
                    <span className="text-xs text-slate-400 shrink-0">
                      {new Date(booking.completedAt).toLocaleDateString(
                        isAr ? "ar" : "en",
                      )}
                    </span>
                  </button>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t space-y-3 shrink-0">
          {/* Channel picker */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {labels.channel}
            </label>
            <div className="flex gap-2">
              {channels.map((ch) => (
                <button
                  key={ch.id}
                  type="button"
                  onClick={() => setChannel(ch.id)}
                  className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border text-sm font-medium transition-colors ${
                    channel === ch.id
                      ? "bg-blue-50 border-blue-300 text-blue-700"
                      : "border-slate-300 text-slate-600 hover:bg-slate-50"
                  }`}
                >
                  <ch.icon className="w-4 h-4" />
                  {ch.label}
                </button>
              ))}
            </div>
          </div>

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

          <div className="flex gap-3 justify-end">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 text-sm"
            >
              {labels.cancel}
            </button>
            <button
              onClick={handleSend}
              disabled={sending || selected.size === 0}
              className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 disabled:opacity-50 text-sm"
            >
              {sending ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Send className="w-4 h-4" />
              )}
              {sending
                ? labels.sending
                : labels.send.replace("{count}", String(selected.size))}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
