"use client";

import { useState, useEffect } from "react";
import { signIn, signOut, useSession } from "next-auth/react";

export interface Inquiry {
  name: string;
  phone: string;
  email: string;
  inquiryType: string;
  message: string;
  agreedTerms: boolean;
  submittedAt: string;
}

export default function AdminInquiries() {
  const { data: session } = useSession();
  const [inquiries, setInquiries] = useState<Inquiry[]>([]);
  const [isDark, setIsDark] = useState(false);
  const [loading, setLoading] = useState(false);
  const [adminUser, setAdminUser] = useState({ username: "", password: "" });
  const [loggedIn, setLoggedIn] = useState(false); // ✅ Track if admin clicked login

  // Detect dark mode
  useEffect(() => {
    const observer = new MutationObserver(() => {
      setIsDark(document.documentElement.classList.contains("dark"));
    });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
    setIsDark(document.documentElement.classList.contains("dark"));
    return () => observer.disconnect();
  }, []);

  // Fetch inquiries after admin login
  const fetchInquiries = async () => {
    if (!loggedIn) return; // ✅ Only fetch after login
    try {
      setLoading(true);
      const res = await fetch("/api/inquiry", { credentials: "include" });
      if (!res.ok) throw new Error("Unauthorized");
      const data: Inquiry[] = await res.json();
      setInquiries(data);
    } catch (err) {
      console.error(err);
      alert("Failed to fetch inquiries. Are you logged in as admin?");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInquiries();
  }, [loggedIn]);

  // Admin login
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    const result = await signIn("credentials", {
      redirect: false,
      username: adminUser.username,
      password: adminUser.password,
    });
    if (result?.error) {
      alert("Invalid credentials");
    } else {
      setLoggedIn(true); // ✅ Mark as logged in
    }
  };

  // Delete all inquiries
  const handleDeleteAll = async () => {
    if (!confirm("Are you sure you want to delete all inquiries?")) return;
    try {
      const res = await fetch("/api/inquiry", { method: "DELETE", credentials: "include" });
      const result = await res.json();
      if (res.ok) {
        alert(result.message);
        setInquiries([]);
      } else {
        alert(result.error || "Failed to delete inquiries.");
      }
    } catch (err) {
      console.error(err);
      alert("Error deleting inquiries.");
    }
  };

  // Theme classes
  const sectionBg = isDark ? "bg-gray-900" : "bg-emerald-50";
  const cardBg = isDark ? "bg-gray-800/90 text-white shadow-2xl border border-emerald-600" : "bg-white shadow-2xl border border-emerald-300";
  const headingText = isDark ? "text-emerald-300" : "text-emerald-900";
  const tableHeader = isDark ? "bg-gray-700 text-emerald-300" : "bg-emerald-100 text-emerald-900";
  const tableRowText = isDark ? "text-emerald-200" : "text-emerald-700";
  const deleteBtn = isDark ? "bg-red-600 hover:bg-red-700" : "bg-red-500 hover:bg-red-600";

  return (
    <section className={`min-h-screen py-16 sm:py-20 md:py-28 px-4 sm:px-6 md:px-12 ${sectionBg}`}>
      <div className={`max-w-5xl mx-auto p-6 rounded-3xl ${cardBg}`}>
        <h2 className={`text-3xl sm:text-4xl md:text-5xl font-bold text-center mb-8 ${headingText}`}>
          Admin Inquiries
        </h2>

        {!loggedIn ? (
          <div className="mb-6 p-4 bg-yellow-200 dark:bg-yellow-700 rounded-lg text-center">
            <p className="mb-2">You must login as admin to view inquiries.</p>
            <form onSubmit={handleLogin} className="flex flex-col sm:flex-row justify-center gap-2">
              <input
                type="text"
                placeholder="Username"
                value={adminUser.username}
                onChange={(e) => setAdminUser((prev) => ({ ...prev, username: e.target.value }))}
                className="px-4 py-2 rounded-xl border"
              />
              <input
                type="password"
                placeholder="Password"
                value={adminUser.password}
                onChange={(e) => setAdminUser((prev) => ({ ...prev, password: e.target.value }))}
                className="px-4 py-2 rounded-xl border"
              />
              <button
                type="submit"
                className="px-6 py-2 bg-emerald-500 text-white rounded-xl hover:bg-emerald-600"
              >
                Login
              </button>
            </form>
          </div>
        ) : (
          <>
            <div className="flex justify-end mb-4">
              <button
                onClick={() => {
                  signOut();
                  setLoggedIn(false); // ✅ reset login state on logout
                  setInquiries([]);
                }}
                className="px-4 py-2 bg-gray-500 text-white rounded-xl hover:bg-gray-600"
              >
                Logout
              </button>
            </div>

            {inquiries.length > 0 && (
              <div className="flex justify-end mb-4">
                <button onClick={handleDeleteAll} className={`px-4 py-2 ${deleteBtn} text-white rounded-full`}>
                  Delete All
                </button>
              </div>
            )}

            {inquiries.length === 0 ? (
              <p className={`text-center text-lg sm:text-xl ${tableRowText}`}>No inquiries submitted yet.</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full border border-emerald-300 text-sm sm:text-base md:text-base">
                  <thead className={tableHeader}>
                    <tr>
                      <th className="border px-2 sm:px-4 py-2">Name</th>
                      <th className="border px-2 sm:px-4 py-2">Phone</th>
                      <th className="border px-2 sm:px-4 py-2">Email</th>
                      <th className="border px-2 sm:px-4 py-2">Inquiry Type</th>
                      <th className="border px-2 sm:px-4 py-2">Message</th>
                      <th className="border px-2 sm:px-4 py-2">Agreed Terms?</th>
                      <th className="border px-2 sm:px-4 py-2">Submitted At</th>
                    </tr>
                  </thead>
                  <tbody>
                    {inquiries.map((inq, idx) => (
                      <tr key={idx} className={`text-center ${tableRowText} break-words`}>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{inq.name}</td>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{inq.phone}</td>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{inq.email}</td>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{inq.inquiryType}</td>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{inq.message}</td>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{inq.agreedTerms ? "✅ Yes" : "❌ No"}</td>
                        <td className="border px-2 sm:px-4 py-1 sm:py-2">{new Date(inq.submittedAt).toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}
      </div>
    </section>
  );
}