"use client";

import { useState } from "react";
import { X, Send, Mail, MessageSquare, Phone } from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Request a Review",
    customerName: "Customer Name",
    customerEmail: "Email (optional)",
    customerPhone: "Phone Number",
    channel: "Send via",
    whatsapp: "WhatsApp",
    email: "Email",
    sms: "SMS",
    send: "Send Request",
    cancel: "Cancel",
    sending: "Sending...",
    success: "Review request sent successfully!",
    error: "Failed to send review request",
    nameRequired: "Customer name is required",
    phoneRequired: "Phone number is required",
  },
  ar: {
    title: "طلب تقييم",
    customerName: "اسم العميل",
    customerEmail: "البريد الإلكتروني (اختياري)",
    customerPhone: "رقم الهاتف",
    channel: "إرسال عبر",
    whatsapp: "واتساب",
    email: "البريد الإلكتروني",
    sms: "رسالة نصية",
    send: "إرسال الطلب",
    cancel: "إلغاء",
    sending: "جاري الإرسال...",
    success: "تم إرسال طلب التقييم بنجاح!",
    error: "فشل في إرسال طلب التقييم",
    nameRequired: "اسم العميل مطلوب",
    phoneRequired: "رقم الهاتف مطلوب",
  },
};

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

export default function ReviewRequestForm({
  lang,
  onClose,
  onSuccess,
}: ReviewRequestFormProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({
    customerName: "",
    customerEmail: "",
    customerPhone: "",
    channel: "whatsapp" as "whatsapp" | "email" | "sms",
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (!form.customerName.trim()) {
      setError(labels.nameRequired);
      return;
    }
    if (!form.customerPhone.trim()) {
      setError(labels.phoneRequired);
      return;
    }

    setLoading(true);
    try {
      const res = await fetchWithCSRF("/api/dashboard/reviews/requests", {
        method: "POST",
        body: JSON.stringify(form),
      });

      if (!res.ok) throw new Error("Failed");

      // Auto-send via the delivery channel (email/WhatsApp/SMS)
      const data = await res.json();
      const requestId = data.reviewRequest?.id;
      if (requestId) {
        await fetchWithCSRF("/api/dashboard/reviews/requests/send", {
          method: "POST",
          body: JSON.stringify({ requestId }),
        }).catch(() => {
          // Non-fatal — request was created, send failure is logged server-side
        });
      }

      onSuccess?.();
      onClose();
      setForm({
        customerName: "",
        customerEmail: "",
        customerPhone: "",
        channel: "whatsapp",
      });
    } catch {
      setError(labels.error);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div
        className="bg-white rounded-xl shadow-xl w-full max-w-md"
        dir={isAr ? "rtl" : "ltr"}
      >
        <div className="flex items-center justify-between p-4 border-b">
          <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>

        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.customerName}
            </label>
            <input
              type="text"
              value={form.customerName}
              onChange={(e) =>
                setForm({ ...form, customerName: e.target.value })
              }
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.customerPhone}
            </label>
            <input
              type="tel"
              value={form.customerPhone}
              onChange={(e) =>
                setForm({ ...form, customerPhone: e.target.value })
              }
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.customerEmail}
            </label>
            <input
              type="email"
              value={form.customerEmail}
              onChange={(e) =>
                setForm({ ...form, customerEmail: e.target.value })
              }
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              {labels.channel}
            </label>
            <div className="flex gap-2">
              {channels.map((ch) => (
                <button
                  key={ch.id}
                  type="button"
                  onClick={() => setForm({ ...form, channel: 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 ${
                    form.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>
          )}

          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50"
            >
              {labels.cancel}
            </button>
            <button
              type="submit"
              disabled={loading}
              className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              <Send className="w-4 h-4" />
              {loading ? labels.sending : labels.send}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
