"use client";

import { useEffect, useMemo, useState } from "react";
import { ColumnDef } from "@tanstack/react-table";
import DataTable from "@/components/common/DataTable";
import CustomLoader from "@/components/common/CustomLoader";

interface Faq {
  id: string;
  question: string;
  answer: string;
  status?: boolean | null;
  created_at?: string | null;
}

interface FormState {
  question: string;
  answer: string;
  status: boolean;
}

const EMPTY_FORM: FormState = {
  question: "",
  answer: "",
  status: true,
};

export default function FaqsPage() {
  const [data, setData] = useState<Faq[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchFaqs = async () => {
    try {
      setLoading(true);

      const response = await fetch("/api/admin/cms/faqs");
      const result = await response.json();

      if (result.success) {
        setData(result.data || []);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

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

  // Lock body scroll while modal is open
  useEffect(() => {
    if (showForm) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }

    return () => {
      document.body.style.overflow = "";
    };
  }, [showForm]);

  const handleAddNew = () => {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setError(null);
    setShowForm(true);
  };

  const handleEdit = (faq: Faq) => {
    setEditingId(faq.id);

    setForm({
      question: faq.question,
      answer: faq.answer,
      status: faq.status ?? true,
    });

    setError(null);
    setShowForm(true);
  };

  const handleCancel = () => {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setError(null);
    setShowForm(false);
  };

  const handleDelete = async (id: string) => {
    const confirmed = window.confirm(
      "Are you sure you want to delete this FAQ?"
    );

    if (!confirmed) return;

    try {
      const response = await fetch(`/api/admin/cms/faqs/${id}`, {
        method: "DELETE",
      });

      const result = await response.json();

      if (result.success) {
        setData((prev) => prev.filter((item) => item.id !== id));

        if (editingId === id) {
          handleCancel();
        }
      } else {
        alert(result.message || "Failed to delete FAQ");
      }
    } catch (error) {
      console.error(error);
      alert("Something went wrong");
    }
  };

  const handleSubmit = async () => {
    setError(null);

    if (!form.question.trim()) {
      setError("Question is required.");
      return;
    }

    if (!form.answer.trim()) {
      setError("Answer is required.");
      return;
    }

    try {
      setSubmitting(true);

      const response = await fetch(
        editingId
          ? `/api/admin/cms/faqs/${editingId}`
          : "/api/admin/cms/faqs",
        {
          method: editingId ? "PUT" : "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(form),
        }
      );

      const result = await response.json();

      if (!result.success) {
        setError(result.message || "Something went wrong.");
        return;
      }

      await fetchFaqs();

      handleCancel();
    } catch (error) {
      console.error(error);
      setError("Something went wrong.");
    } finally {
      setSubmitting(false);
    }
  };

  const columns = useMemo<ColumnDef<Faq>[]>(
    () => [
      {
        accessorKey: "question",
        header: "Question",
        cell: ({ getValue }) => {
          const value = getValue() as string;

          return value.length > 80
            ? `${value.substring(0, 80)}...`
            : value;
        },
      },
      {
        accessorKey: "answer",
        header: "Answer",
        cell: ({ getValue }) => {
          const value = getValue() as string;

          return (
            <span className="text-muted">
              {value.length > 100
                ? `${value.substring(0, 100)}...`
                : value}
            </span>
          );
        },
      },
      {
        accessorKey: "status",
        header: "Status",
        cell: ({ getValue }) => {
          const active = getValue() as boolean;

          return (
            <span
              className={`badge bg-${active ? "success" : "danger"
                }`}
            >
              {active ? "Active" : "Inactive"}
            </span>
          );
        },
      },
      {
        header: "Actions",
        cell: ({ row }) => {
          const faq = row.original;

          return (
            <div className="d-flex gap-2">
              <button
                className="btn btn-warning btn-sm table-action-btn"
                onClick={() => handleEdit(faq)}
              >
                <i className="bi bi-pencil-square"></i>
              </button>

              <button
                className="btn btn-danger btn-sm table-action-btn"
                onClick={() => handleDelete(faq.id)}
              >
                <i className="bi bi-trash"></i>
              </button>
            </div>
          );
        },
      },
    ],
    []
  );

  return (
    <div className="admin-page-wrapper">
      {/* Header */}
      <div className="admin-page-header mb-4">
        <div className="d-flex justify-content-between align-items-center">
          <div>
            <h2 className="admin-page-title">FAQs</h2>
            <p className="admin-page-subtitle">
              Manage frequently asked questions
            </p>
          </div>

          <button
            className="admin-theme-btn"
            onClick={handleAddNew}
          >
            + Add New FAQ
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="admin-table-section">
        {loading ? (
          <CustomLoader />
        ) : (
          <DataTable
            columns={columns}
            data={data}
          />
        )}
      </div>

      {/* Modal */}
      {showForm && (
        <>
          <div
            className="modal fade show"
            style={{ display: "block" }}
            tabIndex={-1}
            role="dialog"
            onClick={handleCancel}
          >
            <div
              className="modal-dialog modal-dialog-centered modal-lg"
              role="document"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="modal-content">
                <div className="modal-header">
                  <h5 className="modal-title fw-semibold">
                    {editingId ? (
                      <>
                        <i className="bi bi-pencil me-2 text-warning" />
                        Edit FAQ
                      </>
                    ) : (
                      <>
                        <i className="bi bi-plus-circle me-2 text-primary" />
                        Add New FAQ
                      </>
                    )}
                  </h5>

                  <button
                    type="button"
                    className="btn-close"
                    onClick={handleCancel}
                  ></button>
                </div>

                <div className="modal-body">
                  {error && (
                    <div className="alert alert-danger">{error}</div>
                  )}

                  <div className="row g-3">
                    <div className="col-12">
                      <label className="form-label">
                        Question <span className="text-danger">*</span>
                      </label>

                      <input
                        type="text"
                        className="form-control"
                        placeholder="Enter question"
                        value={form.question}
                        onChange={(e) =>
                          setForm((prev) => ({
                            ...prev,
                            question: e.target.value,
                          }))
                        }
                      />
                    </div>

                    <div className="col-12">
                      <label className="form-label">
                        Answer <span className="text-danger">*</span>
                      </label>

                      <textarea
                        className="form-control"
                        rows={5}
                        placeholder="Enter answer"
                        value={form.answer}
                        onChange={(e) =>
                          setForm((prev) => ({
                            ...prev,
                            answer: e.target.value,
                          }))
                        }
                      />
                    </div>

                    <div className="col-md-4">
                      <div className="form-check form-switch mt-2">
                        <input
                          className="form-check-input"
                          type="checkbox"
                          id="faqStatus"
                          checked={form.status}
                          onChange={(e) =>
                            setForm((prev) => ({
                              ...prev,
                              status: e.target.checked,
                            }))
                          }
                        />

                        <label
                          className="form-check-label"
                          htmlFor="faqStatus"
                        >
                          {form.status ? "Active" : "Inactive"}
                        </label>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="modal-footer">
                  <button
                    className="btn btn-light px-4"
                    onClick={handleCancel}
                  >
                    Cancel
                  </button>

                  <button
                    className="admin-theme-btn"
                    disabled={submitting}
                    onClick={handleSubmit}
                  >
                    {submitting ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2"></span>
                        Saving...
                      </>
                    ) : editingId ? (
                      <>
                        <i className="bi bi-check-circle me-1" />
                        Update FAQ
                      </>
                    ) : (
                      <>
                        <i className="bi bi-plus-circle me-1" /> Add FAQ
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="modal-backdrop fade show"></div>
        </>
      )}
    </div>
  );
}