"use client";

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

interface Contact {
  id: string;
  section_name: string;
  html_content?: string | null;
  in_person_heading?: string | null;
  in_person_content?: string | null;
  status?: boolean | null;
}

interface Studio {
  id: string;
  studio_name: string;
  address: string;
  address_map_url?: string | null;
  map_embed_url?: string | null;
  email?: string | null;
  phone?: string | null;
  status?: boolean | null;
}

interface FormState {
  section_name: string;
  html_content: string;
  in_person_heading: string;
  in_person_content: string;
  status: boolean;
}

const EMPTY_FORM: FormState = {
  section_name: "",
  html_content: "",
  in_person_heading: "In-Person",
  in_person_content: "",
  status: true,
};

const EMPTY_STUDIO: Omit<Studio, "id"> = {
  studio_name: "",
  address: "",
  address_map_url: "",
  map_embed_url: "",
  email: "",
  phone: "",
  status: true,
};

export default function ContactCmsPage() {
  const [existing, setExisting] = useState<Contact | null>(null);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [studios, setStudios] = useState<Studio[]>([]);
  const [studiosLoading, setStudiosLoading] = useState(true);
  const [studioForm, setStudioForm] = useState<Omit<Studio, "id"> | Studio>(EMPTY_STUDIO);
  const [editingStudioId, setEditingStudioId] = useState<string | null>(null);
  const [studioSubmitting, setStudioSubmitting] = useState(false);
  const [studioError, setStudioError] = useState<string | null>(null);

  // ----- Main content -----

  const fetchContact = async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/admin/cms/contact");
      const result = await response.json();

      if (result.success) {
        const item: Contact | null = result.data;
        setExisting(item);

        if (item) {
          setForm({
            section_name: item.section_name ?? "",
            html_content: item.html_content ?? "",
            in_person_heading: item.in_person_heading ?? "In-Person",
            in_person_content: item.in_person_content ?? "",
            status: item.status ?? true,
          });
        } else {
          setForm(EMPTY_FORM);
        }
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const fetchStudios = async () => {
    try {
      setStudiosLoading(true);
      const response = await fetch("/api/admin/cms/contact/studios");
      const result = await response.json();
      if (result.success) setStudios(result.data);
    } catch (err) {
      console.error(err);
    } finally {
      setStudiosLoading(false);
    }
  };

  useEffect(() => {
    fetchContact();
    fetchStudios();
  }, []);

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

    if (!form.section_name.trim()) {
      setError("Section name is required.");
      return;
    }

    try {
      setSubmitting(true);

      const payload: any = { ...form };
      if (existing) payload.id = existing.id;

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

      const result = await response.json();

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

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

  // ----- Studios -----

  const resetStudioForm = () => {
    setStudioForm(EMPTY_STUDIO);
    setEditingStudioId(null);
    setStudioError(null);
  };

  const handleEditStudio = (studio: Studio) => {
    setStudioForm(studio);
    setEditingStudioId(studio.id);
    setStudioError(null);
  };

  const handleStudioSubmit = async () => {
    setStudioError(null);

    if (!studioForm.studio_name.trim() || !studioForm.address.trim()) {
      setStudioError("Studio name and address are required.");
      return;
    }

    try {
      setStudioSubmitting(true);

      const payload: any = { ...studioForm };
      if (editingStudioId) payload.id = editingStudioId;

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

      const result = await response.json();

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

      resetStudioForm();
      await fetchStudios();
    } catch (err) {
      console.error(err);
      setStudioError("Something went wrong.");
    } finally {
      setStudioSubmitting(false);
    }
  };

  const handleDeleteStudio = async (id: string) => {
    if (!confirm("Delete this studio? This cannot be undone.")) return;

    try {
      const response = await fetch(`/api/admin/cms/contact/studios?id=${id}`, {
        method: "DELETE",
      });
      const result = await response.json();

      if (result.success) {
        setStudios((prev) => prev.filter((s) => s.id !== id));
        if (editingStudioId === id) resetStudioForm();
      }
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div className="admin-page-wrapper">
      <div className="admin-page-header mb-4">
        <div>
          <h2 className="admin-page-title">Contact Us</h2>
          <p className="admin-page-subtitle">
            Manage the Contact Us page content
          </p>
        </div>
      </div>

      {/* ---------- Main content block ---------- */}
      {loading ? (
        <CustomLoader />
      ) : (
        <div className="admin-form-section card mb-4">
          <div className="card-body">
            <h5 className="mb-3">Intro Section</h5>

            {error && <div className="alert alert-danger">{error}</div>}

            <div className="row gx-3">
              <div className="col-12 mb-3">
                <label className="form-label">
                  Section Heading <span className="text-danger">*</span>
                </label>
                <input
                  type="text"
                  className="form-control"
                  placeholder="e.g. Contact RKDA"
                  value={form.section_name}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, section_name: e.target.value }))
                  }
                />
              </div>

              <div className="col-12 mb-3">
                <label className="form-label">Intro Content</label>
                <div className="w-100 overflow-hidden">
                  <RichTextEditor
                    value={form.html_content}
                    onChange={(value) =>
                      setForm((prev) => ({ ...prev, html_content: value }))
                    }
                    uploadEndpoint="/api/admin/cms/contact/upload-image"
                    placeholder="Write the intro paragraph / bullet list here..."
                  />
                </div>
              </div>

              <hr className="my-2" />

              <div className="col-12 mb-3">
                <label className="form-label">In-Person Heading</label>
                <input
                  type="text"
                  className="form-control"
                  placeholder="e.g. In-Person"
                  value={form.in_person_heading}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, in_person_heading: e.target.value }))
                  }
                />
              </div>

              <div className="col-12 mb-3">
                <label className="form-label">In-Person Description</label>
                <textarea
                  className="form-control"
                  rows={3}
                  placeholder="e.g. Currently we have 2 studios in Michigan..."
                  value={form.in_person_content}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, in_person_content: e.target.value }))
                  }
                />
              </div>

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

            <div className="d-flex justify-content-end mt-4">
              <button
                className="admin-theme-btn"
                disabled={submitting}
                onClick={handleSubmit}
              >
                {submitting ? (
                  <>
                    <span className="spinner-border spinner-border-sm me-2"></span>
                    Saving...
                  </>
                ) : existing ? (
                  <>
                    <i className="bi bi-check-circle me-1" /> Update
                  </>
                ) : (
                  <>
                    <i className="bi bi-plus-circle me-1" /> Add
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ---------- Studios ---------- */}
      <div className="admin-form-section card">
        <div className="card-body">
          <h5 className="mb-3">
            {editingStudioId ? "Edit Studio" : "Add Studio"}
          </h5>

          {studioError && <div className="alert alert-danger">{studioError}</div>}

          <div className="row gx-3">
            <div className="col-md-6 col-12 mb-3">
              <label className="form-label">
                Studio Name <span className="text-danger">*</span>
              </label>
              <input
                type="text"
                className="form-control"
                placeholder="e.g. Studio 1"
                value={studioForm.studio_name}
                onChange={(e) =>
                  setStudioForm((prev) => ({ ...prev, studio_name: e.target.value }))
                }
              />
            </div>

            <div className="col-md-6 col-12 mb-3">
              <label className="form-label">
                Address <span className="text-danger">*</span>
              </label>
              <input
                type="text"
                className="form-control"
                placeholder="e.g. 3224 Alpine Rd, Troy, MI 48084"
                value={studioForm.address}
                onChange={(e) =>
                  setStudioForm((prev) => ({ ...prev, address: e.target.value }))
                }
              />
            </div>

            <div className="col-md-6 col-12 mb-3">
              <label className="form-label">"Open in Maps" Link</label>
              <input
                type="text"
                className="form-control"
                placeholder="https://goo.gl/maps/..."
                value={studioForm.address_map_url ?? ""}
                onChange={(e) =>
                  setStudioForm((prev) => ({ ...prev, address_map_url: e.target.value }))
                }
              />
            </div>

            <div className="col-md-6 col-12 mb-3">
              <label className="form-label">Map Embed URL</label>
              <input
                type="text"
                className="form-control"
                placeholder="https://www.google.com/maps?q=...&output=embed"
                value={studioForm.map_embed_url ?? ""}
                onChange={(e) =>
                  setStudioForm((prev) => ({ ...prev, map_embed_url: e.target.value }))
                }
              />
            </div>

            <div className="col-md-6 col-12 mb-3">
              <label className="form-label">Email</label>
              <input
                type="email"
                className="form-control"
                placeholder="e.g. rkda.org@gmail.com"
                value={studioForm.email ?? ""}
                onChange={(e) =>
                  setStudioForm((prev) => ({ ...prev, email: e.target.value }))
                }
              />
            </div>

            <div className="col-md-6 col-12 mb-3">
              <label className="form-label">Phone</label>
              <input
                type="text"
                className="form-control"
                placeholder="e.g. 248-761-3901"
                value={studioForm.phone ?? ""}
                onChange={(e) =>
                  setStudioForm((prev) => ({ ...prev, phone: e.target.value }))
                }
              />
            </div>

            <div className="col-12">
              <div className="form-check form-switch mt-2">
                <input
                  className="form-check-input"
                  type="checkbox"
                  id="studioStatus"
                  checked={studioForm.status ?? true}
                  onChange={(e) =>
                    setStudioForm((prev) => ({ ...prev, status: e.target.checked }))
                  }
                />
                <label className="form-check-label" htmlFor="studioStatus">
                  {studioForm.status ? "Active" : "Inactive"}
                </label>
              </div>
            </div>
          </div>

          <div className="d-flex justify-content-end gap-2 mt-4">
            {editingStudioId && (
              <button className="btn btn-outline-secondary" onClick={resetStudioForm}>
                Cancel
              </button>
            )}
            <button
              className="admin-theme-btn"
              disabled={studioSubmitting}
              onClick={handleStudioSubmit}
            >
              {studioSubmitting ? (
                <>
                  <span className="spinner-border spinner-border-sm me-2"></span>
                  Saving...
                </>
              ) : editingStudioId ? (
                <>
                  <i className="bi bi-check-circle me-1" /> Update Studio
                </>
              ) : (
                <>
                  <i className="bi bi-plus-circle me-1" /> Add Studio
                </>
              )}
            </button>
          </div>
        </div>

        <div className="card-body pt-0">
          <h5 className="mb-2">Studios List</h5>

          {studiosLoading ? (
            <CustomLoader />
          ) : studios.length === 0 ? (
            <div className="text-muted">No studios added yet.</div>
          ) : (
            <div className="table-responsive">
              <table className="custom-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Phone</th>
                    <th>Status</th>
                    <th className="text-end">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {studios.map((studio) => (
                    <tr key={studio.id}>
                      <td>{studio.studio_name}</td>
                      <td>{studio.address}</td>
                      <td>{studio.phone || "-"}</td>
                      <td>
                        <span
                          className={`badge ${
                            studio.status ? "bg-success" : "bg-secondary"
                          }`}
                        >
                          {studio.status ? "Active" : "Inactive"}
                        </span>
                      </td>
                      <td className="text-end">
                        <div className="d-flex gap-1 justify-content-end">
                          <button
                            className="btn btn-warning btn-sm table-action-btn"
                            onClick={() => handleEditStudio(studio)}
                          >
                            <i className="bi bi-pencil-square"></i>
                          </button>
                          <button
                            className="btn btn-danger btn-sm table-action-btn"
                            onClick={() => handleDeleteStudio(studio.id)}
                          >
                            <i className="bi bi-trash" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}