"use client";

import { useEffect, useRef, useState } from "react";
import CustomLoader from "@/components/common/CustomLoader";
import RichTextEditor from "@/components/common/RichTextEditor";

interface ServerSection {
  id: string;
  title: string;
  html_content?: string | null;
  sort_order?: number | null;
  status?: boolean | null;
}

interface SectionRow {
  clientId: string;
  id: string | null; // null means not yet saved to the server
  title: string;
  html_content: string;
  sort_order: number;
  status: boolean;
  submitting: boolean;
  deleting: boolean;
  error: string | null;
  saved: boolean; // briefly shows a "Saved" confirmation
}

const makeClientId = () =>
  `new-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;

const emptyRow = (sortOrder: number): SectionRow => ({
  clientId: makeClientId(),
  id: null,
  title: "",
  html_content: "",
  sort_order: sortOrder,
  status: true,
  submitting: false,
  deleting: false,
  error: null,
  saved: false,
});

export default function SupportUsCmsPage() {
  const [rows, setRows] = useState<SectionRow[]>([]);
  const [loading, setLoading] = useState(true);
  const rowRefs = useRef<Record<string, HTMLDivElement | null>>({});

  const fetchSections = async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/admin/cms/support-us/sections");
      const result = await response.json();

      if (result.success) {
        const items: ServerSection[] = result.data;

        if (items.length === 0) {
          setRows([emptyRow(0)]);
        } else {
          setRows(
            items.map((item) => ({
              clientId: item.id,
              id: item.id,
              title: item.title ?? "",
              html_content: item.html_content ?? "",
              sort_order: item.sort_order ?? 0,
              status: item.status ?? true,
              submitting: false,
              deleting: false,
              error: null,
              saved: false,
            }))
          );
        }
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const updateRow = (clientId: string, patch: Partial<SectionRow>) => {
    setRows((prev) =>
      prev.map((row) => (row.clientId === clientId ? { ...row, ...patch } : row))
    );
  };

  const scrollToRow = (clientId: string) => {
    setTimeout(() => {
      rowRefs.current[clientId]?.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 50);
  };

  const handleAddSection = () => {
    const nextSortOrder =
      rows.length > 0 ? Math.max(...rows.map((r) => r.sort_order)) + 1 : 0;
    const newRow = emptyRow(nextSortOrder);

    setRows((prev) => [...prev, newRow]);
    scrollToRow(newRow.clientId);
  };

  const handleSaveRow = async (clientId: string) => {
    const row = rows.find((r) => r.clientId === clientId);
    if (!row) return;

    if (!row.title.trim()) {
      updateRow(clientId, { error: "Title is required." });
      return;
    }

    updateRow(clientId, { submitting: true, error: null, saved: false });

    try {
      const payload: any = {
        title: row.title,
        html_content: row.html_content,
        sort_order: row.sort_order,
        status: row.status,
      };
      if (row.id) payload.id = row.id;

      const response = await fetch("/api/admin/cms/support-us/sections", {
        method: row.id ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const result = await response.json();

      if (!result.success) {
        updateRow(clientId, {
          submitting: false,
          error: result.message || "Something went wrong.",
        });
        return;
      }

      updateRow(clientId, {
        submitting: false,
        saved: true,
        id: result.data.id,
      });

      setTimeout(() => updateRow(clientId, { saved: false }), 2000);
    } catch (err) {
      console.error(err);
      updateRow(clientId, { submitting: false, error: "Something went wrong." });
    }
  };

  const handleDeleteRow = async (clientId: string) => {
    const row = rows.find((r) => r.clientId === clientId);
    if (!row) return;

    // Not yet saved — just remove locally, no confirm needed
    if (!row.id) {
      setRows((prev) => prev.filter((r) => r.clientId !== clientId));
      delete rowRefs.current[clientId];
      return;
    }

    if (!confirm("Delete this section? This cannot be undone.")) return;

    updateRow(clientId, { deleting: true });

    try {
      const response = await fetch(
        `/api/admin/cms/support-us/sections?id=${row.id}`,
        { method: "DELETE" }
      );
      const result = await response.json();

      if (result.success) {
        setRows((prev) => prev.filter((r) => r.clientId !== clientId));
        delete rowRefs.current[clientId];
      } else {
        updateRow(clientId, { deleting: false, error: result.message || "Failed to delete." });
      }
    } catch (err) {
      console.error(err);
      updateRow(clientId, { deleting: false, error: "Failed to delete." });
    }
  };

  return (
    <div className="admin-page-wrapper">
      <div className="admin-page-header mb-4 d-flex justify-content-between align-items-start flex-wrap gap-2">
        <div>
          <h2 className="admin-page-title">Support Us</h2>
          <p className="admin-page-subtitle">
            Manage the "Support Us" / "Help Us Help You" page content
          </p>
        </div>

        <button className="admin-theme-btn" onClick={handleAddSection}>
          <i className="bi bi-plus-circle me-1" /> Add Another Section
        </button>
      </div>

      {loading ? (
        <CustomLoader />
      ) : (
        <div className="d-flex flex-column gap-4">
          {rows.map((row, index) => (
            <div
              className="admin-form-section card"
              key={row.clientId}
              ref={(el) => {
                rowRefs.current[row.clientId] = el;
              }}
            >
              <div className="card-body">
                <div className="d-flex justify-content-between align-items-center mb-3">
                  <h5 className="mb-0">
                    Section {index + 1}
                    {!row.id && <span className="text-muted small ms-2">(unsaved)</span>}
                  </h5>

                  <button
                    className="btn btn-sm btn-outline-danger"
                    disabled={row.deleting}
                    onClick={() => handleDeleteRow(row.clientId)}
                  >
                    {row.deleting ? (
                      <span className="spinner-border spinner-border-sm" />
                    ) : (
                      <>
                        <i className="bi bi-trash me-1" /> Remove
                      </>
                    )}
                  </button>
                </div>

                {row.error && <div className="alert alert-danger">{row.error}</div>}
                {row.saved && (
                  <div className="alert alert-success py-2">Saved successfully.</div>
                )}

                <div className="row gx-3">
                  <div className="col-md-8 col-12 mb-3">
                    <label className="form-label">
                      Section Title <span className="text-danger">*</span>
                    </label>
                    <input
                      type="text"
                      className="form-control"
                      placeholder="e.g. Student Scholarship Program"
                      value={row.title}
                      onChange={(e) => updateRow(row.clientId, { title: e.target.value })}
                    />
                  </div>

                  <div className="col-md-4 col-12 mb-3">
                    <label className="form-label">Sort Order</label>
                    <input
                      type="number"
                      className="form-control"
                      value={row.sort_order}
                      onChange={(e) =>
                        updateRow(row.clientId, { sort_order: Number(e.target.value) })
                      }
                      min={0}
                    />
                  </div>

                  <div className="col-12 mb-3">
                    <label className="form-label">Content</label>
                    <div className="w-100 overflow-hidden">
                      <RichTextEditor
                        value={row.html_content}
                        onChange={(value) => updateRow(row.clientId, { html_content: value })}
                        uploadEndpoint="/api/admin/cms/support-us/upload-image"
                        placeholder="Write the section description here. For pricing tiers, use the editor's table/list tools directly (e.g. 12 months - $1200)..."
                      />
                    </div>
                  </div>

                  <div className="col-12">
                    <div className="form-check form-switch mt-2">
                      <input
                        className="form-check-input"
                        type="checkbox"
                        id={`status-${row.clientId}`}
                        checked={row.status}
                        onChange={(e) =>
                          updateRow(row.clientId, { status: e.target.checked })
                        }
                      />
                      <label className="form-check-label" htmlFor={`status-${row.clientId}`}>
                        {row.status ? "Active" : "Inactive"}
                      </label>
                    </div>
                  </div>
                </div>

                <div className="d-flex justify-content-end mt-3">
                  <button
                    className="admin-theme-btn"
                    disabled={row.submitting}
                    onClick={() => handleSaveRow(row.clientId)}
                  >
                    {row.submitting ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2"></span>
                        Saving...
                      </>
                    ) : row.id ? (
                      <>
                        <i className="bi bi-check-circle me-1" /> Update Section
                      </>
                    ) : (
                      <>
                        <i className="bi bi-plus-circle me-1" /> Save Section
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          ))}

          <button
            className="btn btn-outline-primary align-self-start"
            onClick={handleAddSection}
          >
            <i className="bi bi-plus-circle me-1" /> Add Another Section
          </button>
        </div>
      )}
    </div>
  );
}