"use client";

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

const t = {
  en: {
    title: "Reply to Review",
    placeholder: "Write your response...",
    send: "Send Response",
    cancel: "Cancel",
    success: "Response sent successfully",
    error: "Failed to send response",
  },
  ar: {
    title: "الرد على التقييم",
    placeholder: "اكتب ردك...",
    send: "إرسال الرد",
    cancel: "إلغاء",
    success: "تم إرسال الرد بنجاح",
    error: "فشل في إرسال الرد",
  },
};

interface ReviewResponseModalProps {
  lang: string;
  reviewId: string;
  customerName: string;
  onClose: () => void;
  onSuccess: () => void;
}

export default function ReviewResponseModal({
  lang,
  reviewId,
  customerName,
  onClose,
  onSuccess,
}: ReviewResponseModalProps) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];
  const [response, setResponse] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!response.trim()) return;

    setLoading(true);
    setError("");

    try {
      const res = await fetchWithCSRF("/api/dashboard/reviews/respond", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reviewId, response: response.trim() }),
      });

      if (!res.ok) throw new Error("Failed");
      onSuccess();
      onClose();
    } catch {
      setError(labels.error);
    } finally {
      setLoading(false);
    }
  }

  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-lg"
        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">
          <p className="text-sm text-slate-500">
            {isAr ? `الرد على ${customerName}` : `Replying to ${customerName}`}
          </p>

          <textarea
            value={response}
            onChange={(e) => setResponse(e.target.value)}
            placeholder={labels.placeholder}
            rows={5}
            className="w-full border border-slate-300 rounded-lg p-3 text-slate-900 placeholder-slate-400 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />

          {error && (
            <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">
              {error}
            </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
              type="submit"
              disabled={loading || !response.trim()}
              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"
            >
              {loading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Send className="w-4 h-4" />
              )}
              {labels.send}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
