"use client"

import { useEffect, useState } from "react"
import api from "@/lib/axios"
import { HelpCircle, CheckCircle, Trash2, XCircle, Search } from "lucide-react"
import Swal from "sweetalert2";

export default function AdminQuestionsPage() {
  const [questions, setQuestions] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [answeringId, setAnsweringId] = useState<string | null>(null)
  const [answerText, setAnswerText] = useState("")

  useEffect(() => {
    loadQuestions()
  }, [])

  const loadQuestions = async () => {
    try {
      const res = await api.get("/admin/questions")
      setQuestions(res.data)
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to delete this question?", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    try {
      await api.delete(`/admin/questions/${id}`)
      setQuestions(questions.filter(q => q.id !== id))
    } catch (error) {
      console.error(error)
      Swal.fire({ text: "Failed to delete question", confirmButtonColor: "#18181b", icon: "error" })
    }
  }

  const handleAnswer = async (id: string) => {
    try {
      await api.put(`/admin/questions/${id}`, { answer: answerText })
      setAnsweringId(null)
      setAnswerText("")
      loadQuestions()
    } catch (error) {
      console.error(error)
      Swal.fire({ text: "Failed to answer question", confirmButtonColor: "#18181b", icon: "error" })
    }
  }

  if (loading) {
    return <div className="p-8 text-center text-zinc-500">Loading questions...</div>
  }

  return (
    <div className="space-y-6 max-w-5xl">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-black text-zinc-950 uppercase tracking-widest flex items-center gap-2">
            <HelpCircle className="w-6 h-6 text-blue-500" />
            Product Q&A
          </h1>
          <p className="text-xs text-zinc-500 font-bold uppercase tracking-wider mt-1">
            Answer customer questions to boost sales and clarity.
          </p>
        </div>
      </div>

      <div className="bg-white border border-zinc-150 rounded-2xl shadow-sm overflow-hidden">
        {questions.length === 0 ? (
          <div className="p-8 text-center text-zinc-500 text-sm">
            No questions found.
          </div>
        ) : (
          <div className="divide-y divide-zinc-100">
            {questions.map((q) => (
              <div key={q.id} className="p-6 transition-colors hover:bg-zinc-50/50">
                <div className="flex justify-between items-start gap-4">
                  <div className="space-y-2 flex-1">
                    <div className="flex items-center gap-2">
                      <span className={`text-[10px] font-black tracking-widest uppercase px-2 py-1 rounded-sm ${
                        q.status === "PENDING" ? "bg-amber-100 text-amber-700" : "bg-emerald-100 text-emerald-700"
                      }`}>
                        {q.status}
                      </span>
                      <span className="text-xs text-zinc-500 font-medium">
                        Product: <a href={`/product/${q.product.slug}`} target="_blank" rel="noreferrer" className="text-blue-500 hover:underline font-bold">{q.product.title}</a>
                      </span>
                      <span className="text-xs text-zinc-400">
                        • {new Date(q.createdAt).toLocaleDateString()}
                      </span>
                    </div>

                    <div className="bg-zinc-50 border border-zinc-100 p-4 rounded-xl mt-3">
                      <p className="text-sm font-semibold text-zinc-900 leading-relaxed mb-2">
                        &quot;{q.question}&quot;
                      </p>
                      <p className="text-[10px] text-zinc-500 font-bold uppercase tracking-wider">
                        Asked by: <span className="text-zinc-800">{q.name}</span> ({q.email})
                      </p>
                    </div>

                    {q.status === "ANSWERED" ? (
                      <div className="bg-blue-50/50 border border-blue-100 p-4 rounded-xl mt-3">
                        <p className="text-xs font-black uppercase tracking-widest text-blue-800 mb-1">Store Answer:</p>
                        <p className="text-sm text-zinc-800">{q.answer}</p>
                      </div>
                    ) : (
                      answeringId === q.id ? (
                        <div className="mt-4 space-y-3">
                          <textarea
                            value={answerText}
                            onChange={(e) => setAnswerText(e.target.value)}
                            placeholder="Write your answer here..."
                            className="w-full border border-zinc-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-zinc-950 outline-none min-h-[100px]"
                          />
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => handleAnswer(q.id)}
                              className="bg-zinc-950 text-white text-xs font-bold px-4 py-2 rounded-lg hover:bg-zinc-800"
                            >
                              Submit Answer
                            </button>
                            <button
                              onClick={() => { setAnsweringId(null); setAnswerText(""); }}
                              className="text-zinc-500 hover:text-zinc-800 text-xs font-bold px-4 py-2"
                            >
                              Cancel
                            </button>
                          </div>
                        </div>
                      ) : (
                        <button
                          onClick={() => { setAnsweringId(q.id); setAnswerText(""); }}
                          className="mt-3 text-blue-600 hover:text-blue-800 text-xs font-bold tracking-wider uppercase flex items-center gap-1"
                        >
                          <HelpCircle className="w-3.5 h-3.5" />
                          Answer Question
                        </button>
                      )
                    )}
                  </div>

                  <div className="flex gap-2">
                    <button
                      onClick={() => handleDelete(q.id)}
                      className="p-2 text-zinc-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition"
                      title="Delete Question"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
