"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Plus,
  Trash2,
  Sparkles,
  Loader2,
  GripVertical,
  ChevronUp,
  ChevronDown,
  Pencil,
  Check,
  X,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Review Questions",
    addQuestion: "Add Question",
    generateAI: "Generate with AI",
    generating: "Generating...",
    questionEn: "Question (English)",
    questionAr: "Question (Arabic)",
    type: "Type",
    rating: "Star Rating",
    text: "Text Input",
    yesno: "Yes / No",
    industry: "Industry",
    save: "Save",
    cancel: "Cancel",
    delete: "Delete",
    noQuestions:
      "No questions configured. Add or generate questions for your review form.",
    loadError: "Failed to load questions",
    saveError: "Failed to save question",
    deleteError: "Failed to delete question",
    generateError: "Failed to generate questions",
    confirmDelete: "Delete this question?",
  },
  ar: {
    title: "أسئلة التقييم",
    addQuestion: "إضافة سؤال",
    generateAI: "إنشاء بالذكاء الاصطناعي",
    generating: "جاري الإنشاء...",
    questionEn: "السؤال (إنجليزي)",
    questionAr: "السؤال (عربي)",
    type: "النوع",
    rating: "تقييم بالنجوم",
    text: "إدخال نصي",
    yesno: "نعم / لا",
    industry: "القطاع",
    save: "حفظ",
    cancel: "إلغاء",
    delete: "حذف",
    noQuestions:
      "لا توجد أسئلة مهيأة. أضف أو أنشئ أسئلة لنموذج التقييم الخاص بك.",
    loadError: "فشل في تحميل الأسئلة",
    saveError: "فشل في حفظ السؤال",
    deleteError: "فشل في حذف السؤال",
    generateError: "فشل في إنشاء الأسئلة",
    confirmDelete: "حذف هذا السؤال؟",
  },
};

interface ReviewQuestion {
  id: string;
  questionEn: string;
  questionAr: string;
  type: "rating" | "text" | "yesno";
  industry: string | null;
  sortOrder: number;
}

interface ReviewQuestionEditorProps {
  lang: string;
}

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

  const [questions, setQuestions] = useState<ReviewQuestion[]>([]);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [error, setError] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({
    questionEn: "",
    questionAr: "",
    type: "rating" as "rating" | "text" | "yesno",
  });
  const [addingNew, setAddingNew] = useState(false);

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

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

  const handleSaveQuestion = async (question: Partial<ReviewQuestion>) => {
    setError("");
    try {
      const isEdit = !!question.id;
      const url = isEdit
        ? `/api/dashboard/reviews/questions/${question.id}`
        : "/api/dashboard/reviews/questions";
      const res = await fetchWithCSRF(url, {
        method: isEdit ? "PUT" : "POST",
        body: JSON.stringify(question),
      });
      if (!res.ok) throw new Error("Failed");
      await fetchQuestions();
      setEditingId(null);
      setAddingNew(false);
    } catch {
      setError(labels.saveError);
    }
  };

  const handleDeleteQuestion = async (id: string) => {
    if (!window.confirm(labels.confirmDelete)) return;
    setError("");
    try {
      const res = await fetchWithCSRF(
        `/api/dashboard/reviews/questions/${id}`,
        {
          method: "DELETE",
        },
      );
      if (!res.ok) throw new Error("Failed");
      setQuestions((prev) => prev.filter((q) => q.id !== id));
    } catch {
      setError(labels.deleteError);
    }
  };

  const handleGenerate = async () => {
    setGenerating(true);
    setError("");
    try {
      // Step 1: Generate questions via AI (preview only, not persisted)
      const res = await fetchWithCSRF(
        "/api/dashboard/reviews/questions/generate",
        {
          method: "POST",
          body: JSON.stringify({
            industry: "general",
            language: isAr ? "ar" : "en",
            count: 5,
          }),
        },
      );
      if (!res.ok) throw new Error("Failed to generate");
      const data = await res.json();
      const generated = data.questions ?? [];

      // Step 2: Save each generated question via the create endpoint
      for (let i = 0; i < generated.length; i++) {
        const q = generated[i];
        await fetchWithCSRF("/api/dashboard/reviews/questions", {
          method: "POST",
          body: JSON.stringify({
            questionEn: q.questionEn ?? q.question_en ?? "",
            questionAr: q.questionAr ?? q.question_ar ?? "",
            type: q.type ?? "text",
            sortOrder: questions.length + i,
          }),
        });
      }

      // Step 3: Refresh the list to show newly saved questions
      await fetchQuestions();
    } catch {
      setError(labels.generateError);
    } finally {
      setGenerating(false);
    }
  };

  const handleReorder = async (index: number, direction: "up" | "down") => {
    const newQuestions = [...questions];
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= newQuestions.length) return;

    [newQuestions[index], newQuestions[targetIndex]] = [
      newQuestions[targetIndex],
      newQuestions[index],
    ];

    const reordered = newQuestions.map((q, i) => ({ ...q, sortOrder: i }));
    setQuestions(reordered);

    try {
      await fetchWithCSRF("/api/dashboard/reviews/questions/reorder", {
        method: "PUT",
        body: JSON.stringify({
          order: reordered.map((q) => ({ id: q.id, sortOrder: q.sortOrder })),
        }),
      });
    } catch {
      /* revert on error */
      await fetchQuestions();
    }
  };

  const startEdit = (question: ReviewQuestion) => {
    setEditingId(question.id);
    setEditForm({
      questionEn: question.questionEn,
      questionAr: question.questionAr,
      type: question.type,
    });
    setAddingNew(false);
  };

  const startAdd = () => {
    setAddingNew(true);
    setEditingId(null);
    setEditForm({ questionEn: "", questionAr: "", type: "text" });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
      </div>
    );
  }

  return (
    <div dir={isAr ? "rtl" : "ltr"} className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold text-slate-900">{labels.title}</h3>
        <div className="flex items-center gap-2">
          <button
            onClick={handleGenerate}
            disabled={generating}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-purple-600/20 text-purple-400 border border-purple-600/30 rounded-lg hover:bg-purple-600/30 text-sm disabled:opacity-50"
          >
            {generating ? (
              <Loader2 className="w-3.5 h-3.5 animate-spin" />
            ) : (
              <Sparkles className="w-3.5 h-3.5" />
            )}
            {generating ? labels.generating : labels.generateAI}
          </button>
          <button
            onClick={startAdd}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 text-sm"
          >
            <Plus className="w-3.5 h-3.5" />
            {labels.addQuestion}
          </button>
        </div>
      </div>

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

      {questions.length === 0 && !addingNew && (
        <div className="text-center py-8 text-slate-500">
          {labels.noQuestions}
        </div>
      )}

      <div className="space-y-2">
        {questions.map((question, index) => (
          <div
            key={question.id}
            className="bg-slate-50 rounded-lg p-4 border border-slate-200"
          >
            {editingId === question.id ? (
              <div className="space-y-3">
                <input
                  value={editForm.questionEn}
                  onChange={(e) =>
                    setEditForm({ ...editForm, questionEn: e.target.value })
                  }
                  placeholder={labels.questionEn}
                  className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
                <input
                  value={editForm.questionAr}
                  onChange={(e) =>
                    setEditForm({ ...editForm, questionAr: e.target.value })
                  }
                  placeholder={labels.questionAr}
                  dir="rtl"
                  className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
                <div className="flex items-center gap-3">
                  <label className="text-sm text-slate-500">
                    {labels.type}:
                  </label>
                  <select
                    value={editForm.type}
                    onChange={(e) =>
                      setEditForm({
                        ...editForm,
                        type: e.target.value as "rating" | "text" | "yesno",
                      })
                    }
                    className="border border-slate-300 rounded-lg px-3 py-1.5 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="rating">{labels.rating}</option>
                    <option value="text">{labels.text}</option>
                    <option value="yesno">{labels.yesno}</option>
                  </select>
                </div>
                <div className="flex gap-2 justify-end">
                  <button
                    onClick={() => setEditingId(null)}
                    className="p-1.5 text-slate-400 hover:text-slate-700"
                  >
                    <X className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() =>
                      handleSaveQuestion({
                        id: question.id,
                        ...editForm,
                      })
                    }
                    className="p-1.5 text-brand-green hover:text-brand-green/80"
                  >
                    <Check className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ) : (
              <div className="flex items-start gap-3">
                <div className="flex flex-col gap-1 pt-1">
                  <button
                    onClick={() => handleReorder(index, "up")}
                    disabled={index === 0}
                    className="text-slate-400 hover:text-slate-700 disabled:opacity-30"
                  >
                    <ChevronUp className="w-4 h-4" />
                  </button>
                  <GripVertical className="w-4 h-4 text-slate-400" />
                  <button
                    onClick={() => handleReorder(index, "down")}
                    disabled={index === questions.length - 1}
                    className="text-slate-400 hover:text-slate-700 disabled:opacity-30"
                  >
                    <ChevronDown className="w-4 h-4" />
                  </button>
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-slate-900">
                    {question.questionEn}
                  </p>
                  <p className="text-sm text-slate-500 mt-0.5" dir="rtl">
                    {question.questionAr}
                  </p>
                  <div className="flex items-center gap-2 mt-2">
                    <span className="text-xs px-2 py-0.5 rounded bg-slate-200 text-slate-600">
                      {question.type === "rating"
                        ? labels.rating
                        : question.type === "yesno"
                          ? labels.yesno
                          : labels.text}
                    </span>
                    {question.industry && (
                      <span className="text-xs px-2 py-0.5 rounded bg-slate-200 text-slate-600">
                        {question.industry}
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => startEdit(question)}
                    className="p-1.5 text-slate-400 hover:text-slate-700"
                  >
                    <Pencil className="w-3.5 h-3.5" />
                  </button>
                  <button
                    onClick={() => handleDeleteQuestion(question.id)}
                    className="p-1.5 text-slate-400 hover:text-red-500"
                  >
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>
            )}
          </div>
        ))}

        {/* Add new question form */}
        {addingNew && (
          <div className="bg-green-50 rounded-lg p-4 border border-brand-green/30 space-y-3">
            <input
              value={editForm.questionEn}
              onChange={(e) =>
                setEditForm({ ...editForm, questionEn: e.target.value })
              }
              placeholder={labels.questionEn}
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              autoFocus
            />
            <input
              value={editForm.questionAr}
              onChange={(e) =>
                setEditForm({ ...editForm, questionAr: e.target.value })
              }
              placeholder={labels.questionAr}
              dir="rtl"
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
            <div className="flex items-center gap-3">
              <label className="text-sm text-slate-500">{labels.type}:</label>
              <select
                value={editForm.type}
                onChange={(e) =>
                  setEditForm({
                    ...editForm,
                    type: e.target.value as "rating" | "text" | "yesno",
                  })
                }
                className="border border-slate-300 rounded-lg px-3 py-1.5 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500"
              >
                <option value="rating">{labels.rating}</option>
                <option value="text">{labels.text}</option>
                <option value="yesno">{labels.yesno}</option>
              </select>
            </div>
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => setAddingNew(false)}
                className="px-3 py-1.5 text-sm text-slate-400 hover:text-slate-700"
              >
                {labels.cancel}
              </button>
              <button
                onClick={() =>
                  handleSaveQuestion({
                    questionEn: editForm.questionEn,
                    questionAr: editForm.questionAr,
                    type: editForm.type,
                    sortOrder: questions.length,
                  })
                }
                disabled={!editForm.questionEn.trim()}
                className="flex items-center gap-1.5 px-3 py-1.5 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 text-sm disabled:opacity-50"
              >
                <Check className="w-3.5 h-3.5" />
                {labels.save}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
