/**
 * ReviewRequestDialog
 * Popup shown when an appointment is marked as completed.
 * Lets the admin choose/edit review questions and send them to the customer.
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  X,
  Mail,
  MessageSquare,
  Plus,
  Trash2,
  Send,
  Loader2,
  Clock,
  Star,
  ChevronRight,
  Phone,
} from "lucide-react";

interface Booking {
  id: string;
  customerName: string;
  customerPhone: string;
  customerEmail?: string | null;
  service: string;
}

interface Question {
  questionEn: string;
  questionAr: string;
}

interface ReviewRequestDialogProps {
  lang: Lang;
  booking: Booking | null;
  isOpen: boolean;
  onClose: () => void;
  onSent: (bookingId: string) => void;
  /** Set to true when the server already auto-sent the review — skips the form */
  autoSent?: boolean;
  autoSentChannel?: "email" | "whatsapp";
}

const DEFAULT_QUESTIONS: Question[] = [
  {
    questionEn: "How would you rate your overall experience?",
    questionAr: "كيف تقيّم تجربتك الإجمالية؟",
  },
  {
    questionEn: "How was the quality of service you received?",
    questionAr: "كيف كانت جودة الخدمة التي تلقيتها؟",
  },
  {
    questionEn: "Was our team professional and attentive?",
    questionAr: "هل كان فريقنا محترفاً ومهتماً؟",
  },
  {
    questionEn: "Would you recommend us to friends or family?",
    questionAr: "هل ستوصي بنا لأصدقائك أو عائلتك؟",
  },
  {
    questionEn: "Is there anything we could have done better?",
    questionAr: "هل هناك أي شيء كان يمكننا القيام به بشكل أفضل؟",
  },
];

export default function ReviewRequestDialog({
  lang,
  booking,
  isOpen,
  onClose,
  onSent,
  autoSent = false,
  autoSentChannel,
}: ReviewRequestDialogProps) {
  const isAr = lang === "ar";

  const [questions, setQuestions] = useState<Question[]>(DEFAULT_QUESTIONS);
  const [loadingQuestions, setLoadingQuestions] = useState(false);
  const [channel, setChannel] = useState<"email" | "whatsapp">("email");
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [newQuestion, setNewQuestion] = useState("");
  const [showAddQuestion, setShowAddQuestion] = useState(false);

  // Auto-select channel based on available contact info
  useEffect(() => {
    if (!booking) return;
    if (booking.customerEmail) {
      setChannel("email");
    } else if (booking.customerPhone) {
      setChannel("whatsapp");
    }
  }, [booking]);

  // Fetch question templates on open
  const fetchQuestions = useCallback(async () => {
    setLoadingQuestions(true);
    try {
      const res = await fetch("/api/dashboard/reviews/questions");
      if (res.ok) {
        const data = await res.json();
        if (data.templates && data.templates.length > 0) {
          const firstTemplate = data.templates[0];
          const templateQuestions = Array.isArray(firstTemplate.questions)
            ? firstTemplate.questions
            : [];
          if (templateQuestions.length > 0) {
            setQuestions(templateQuestions);
          }
        }
      }
    } catch {
      // Fall back to defaults silently
    } finally {
      setLoadingQuestions(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen && booking) {
      setError(null);
      setShowAddQuestion(false);
      setNewQuestion("");
      if (autoSent) {
        // Server already sent the review — jump straight to success
        setSent(true);
        if (autoSentChannel) setChannel(autoSentChannel);
        onSent(booking.id);
      } else {
        setSent(false);
        fetchQuestions();
      }
    }
  }, [isOpen, booking, autoSent, autoSentChannel, fetchQuestions, onSent]);

  const removeQuestion = (idx: number) => {
    setQuestions((prev) => prev.filter((_, i) => i !== idx));
  };

  const addQuestion = () => {
    if (!newQuestion.trim()) return;
    setQuestions((prev) => [
      ...prev,
      { questionEn: newQuestion.trim(), questionAr: newQuestion.trim() },
    ]);
    setNewQuestion("");
    setShowAddQuestion(false);
  };

  const handleSend = async () => {
    if (!booking) return;
    setSending(true);
    setError(null);

    try {
      // 1. Create the review request
      const createRes = await fetchWithCSRF("/api/dashboard/reviews/requests", {
        method: "POST",
        body: JSON.stringify({
          customerName: booking.customerName,
          customerEmail: booking.customerEmail ?? null,
          customerPhone: booking.customerPhone ?? null,
          channel,
          language: isAr ? "ar" : "en",
          bookingId: booking.id,
          source: "manual",
          questions,
        }),
      });

      const createData = await createRes.json();
      if (!createData.success) {
        throw new Error(createData.error || "Failed to create review request");
      }

      const requestId = createData.reviewRequest.id;

      // 2. Send it (queues email/WhatsApp delivery)
      const sendRes = await fetchWithCSRF(
        "/api/dashboard/reviews/requests/send",
        {
          method: "POST",
          body: JSON.stringify({ requestId }),
        },
      );

      const sendData = await sendRes.json();
      if (!sendData.success) {
        throw new Error(sendData.error || "Failed to send review request");
      }

      setSent(true);
      onSent(booking.id);
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "حدث خطأ أثناء الإرسال"
            : "Failed to send review request",
      );
    } finally {
      setSending(false);
    }
  };

  if (!isOpen || !booking) return null;

  const hasEmail = Boolean(booking.customerEmail);
  const hasPhone = Boolean(booking.customerPhone);

  return (
    /* Backdrop */
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="relative w-full max-w-lg rounded-2xl bg-white shadow-2xl"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* ── Header ── */}
        <div className="flex items-center justify-between border-b border-slate-100 px-6 py-4">
          <div className="flex items-center gap-2">
            <Star className="h-5 w-5 text-amber-400 fill-amber-400" />
            <h2 className="text-base font-semibold text-slate-900">
              {isAr ? "إرسال طلب تقييم" : "Send Review Request"}
            </h2>
          </div>
          <button
            onClick={onClose}
            className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {sent ? (
          /* ── Success State ── */
          <div className="px-6 py-8 text-center">
            <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-50">
              <Clock className="h-8 w-8 text-emerald-500" />
            </div>
            <h3 className="mb-2 text-lg font-semibold text-slate-900">
              {isAr ? "في انتظار التقييم" : "Awaiting Feedback"}
            </h3>
            <p className="mb-1 text-sm font-medium text-slate-700">
              {booking.customerName}
            </p>
            <p className="mb-6 text-sm text-slate-500">
              {isAr
                ? `تم إرسال رابط التقييم عبر ${channel === "email" ? "البريد الإلكتروني" : "واتساب"}. سيتلقون تذكيراً إذا لم يردوا خلال 3 أيام.`
                : `Review link sent via ${channel === "email" ? "email" : "WhatsApp"}. They'll receive a reminder if they haven't responded in 3 days.`}
            </p>
            <div className="flex gap-3 justify-center">
              <a
                href={`/${lang}/dashboard?tab=reviews&sub=requests`}
                className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
              >
                {isAr ? "عرض في تبويب التقييمات" : "View in Reviews Tab"}
                <ChevronRight className="h-3.5 w-3.5" />
              </a>
              <button
                onClick={onClose}
                className="rounded-lg bg-emerald-500 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-600 transition-colors"
              >
                {isAr ? "إغلاق" : "Close"}
              </button>
            </div>
          </div>
        ) : (
          /* ── Form State ── */
          <>
            {/* Customer info */}
            <div className="px-6 pt-4 pb-3">
              <div className="rounded-xl bg-slate-50 border border-slate-100 px-4 py-3">
                <div className="flex items-start gap-3">
                  <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-700 text-sm font-semibold">
                    {booking.customerName.charAt(0).toUpperCase()}
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-slate-900 truncate">
                      {booking.customerName}
                    </p>
                    <p className="text-xs text-slate-500 truncate">
                      {booking.service}
                    </p>
                    <div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5">
                      {booking.customerEmail && (
                        <span className="inline-flex items-center gap-1 text-xs text-slate-400">
                          <Mail className="h-3 w-3" />
                          {booking.customerEmail}
                        </span>
                      )}
                      {booking.customerPhone && (
                        <span className="inline-flex items-center gap-1 text-xs text-slate-400">
                          <Phone className="h-3 w-3" />
                          {booking.customerPhone}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Channel selector */}
            <div className="px-6 pb-3">
              <p className="mb-2 text-xs font-medium text-slate-500 uppercase tracking-wide">
                {isAr ? "قناة الإرسال" : "Send via"}
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setChannel("email")}
                  disabled={!hasEmail}
                  title={
                    !hasEmail
                      ? isAr
                        ? "لا يوجد بريد إلكتروني"
                        : "No email available"
                      : undefined
                  }
                  className={`flex-1 flex items-center justify-center gap-2 rounded-lg border py-2 text-sm font-medium transition-all ${
                    channel === "email"
                      ? "border-emerald-500 bg-emerald-50 text-emerald-700"
                      : "border-slate-200 bg-white text-slate-500 hover:border-slate-300"
                  } disabled:opacity-40 disabled:cursor-not-allowed`}
                >
                  <Mail className="h-3.5 w-3.5" />
                  {isAr ? "بريد إلكتروني" : "Email"}
                </button>
                <button
                  onClick={() => setChannel("whatsapp")}
                  disabled={!hasPhone}
                  title={
                    !hasPhone
                      ? isAr
                        ? "لا يوجد رقم هاتف"
                        : "No phone available"
                      : undefined
                  }
                  className={`flex-1 flex items-center justify-center gap-2 rounded-lg border py-2 text-sm font-medium transition-all ${
                    channel === "whatsapp"
                      ? "border-emerald-500 bg-emerald-50 text-emerald-700"
                      : "border-slate-200 bg-white text-slate-500 hover:border-slate-300"
                  } disabled:opacity-40 disabled:cursor-not-allowed`}
                >
                  <MessageSquare className="h-3.5 w-3.5" />
                  WhatsApp
                </button>
              </div>
            </div>

            {/* Questions list */}
            <div className="px-6 pb-3">
              <p className="mb-2 text-xs font-medium text-slate-500 uppercase tracking-wide">
                {isAr ? "الأسئلة" : "Review Questions"}
                {loadingQuestions && (
                  <Loader2 className="ml-1.5 inline h-3 w-3 animate-spin text-slate-400" />
                )}
              </p>
              <ul className="space-y-1.5 max-h-48 overflow-y-auto pr-1">
                {questions.map((q, idx) => (
                  <li
                    key={idx}
                    className="flex items-start gap-2 rounded-lg border border-slate-100 bg-slate-50 px-3 py-2.5"
                  >
                    <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-[10px] font-bold text-emerald-700">
                      {idx + 1}
                    </span>
                    <span className="flex-1 text-sm text-slate-700 leading-snug">
                      {isAr && q.questionAr ? q.questionAr : q.questionEn}
                    </span>
                    <button
                      onClick={() => removeQuestion(idx)}
                      className="shrink-0 mt-0.5 text-slate-300 hover:text-red-400 transition-colors"
                      title={isAr ? "حذف السؤال" : "Remove question"}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </li>
                ))}
              </ul>

              {/* Add question */}
              {showAddQuestion ? (
                <div className="mt-2 flex gap-2">
                  <input
                    type="text"
                    value={newQuestion}
                    onChange={(e) => setNewQuestion(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") addQuestion();
                      if (e.key === "Escape") setShowAddQuestion(false);
                    }}
                    placeholder={
                      isAr ? "اكتب سؤالاً جديداً..." : "Type a new question..."
                    }
                    autoFocus
                    className="flex-1 rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700 placeholder:text-slate-400 focus:border-emerald-400 focus:outline-none focus:ring-1 focus:ring-emerald-400"
                  />
                  <button
                    onClick={addQuestion}
                    disabled={!newQuestion.trim()}
                    className="rounded-lg bg-emerald-500 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-600 disabled:opacity-40 transition-colors"
                  >
                    {isAr ? "إضافة" : "Add"}
                  </button>
                </div>
              ) : (
                <button
                  onClick={() => setShowAddQuestion(true)}
                  className="mt-2 flex items-center gap-1.5 text-xs text-slate-400 hover:text-emerald-600 transition-colors"
                >
                  <Plus className="h-3.5 w-3.5" />
                  {isAr ? "إضافة سؤال" : "Add question"}
                </button>
              )}
            </div>

            {/* Error */}
            {error && (
              <div className="mx-6 mb-3 rounded-lg bg-red-50 border border-red-100 px-3 py-2 text-sm text-red-600">
                {error}
              </div>
            )}

            {/* Footer */}
            <div className="flex items-center justify-between border-t border-slate-100 px-6 py-4">
              <button
                onClick={onClose}
                className="text-sm text-slate-400 hover:text-slate-600 transition-colors"
              >
                {isAr ? "تخطّ الآن" : "Skip for now"}
              </button>
              <button
                onClick={handleSend}
                disabled={
                  sending || questions.length === 0 || (!hasEmail && !hasPhone)
                }
                className="inline-flex items-center gap-2 rounded-lg bg-emerald-500 px-5 py-2.5 text-sm font-semibold text-white hover:bg-emerald-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-sm"
              >
                {sending ? (
                  <>
                    <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    {isAr ? "جاري الإرسال..." : "Sending..."}
                  </>
                ) : (
                  <>
                    <Send className="h-3.5 w-3.5" />
                    {isAr ? "إرسال طلب التقييم" : "Send Review Request"}
                  </>
                )}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
