"use client";

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

interface About {
  id: string;
  page_id: string;
  section_name: string;
  image?: string | null;
  html_content?: string | null;
  status?: boolean | null;
}

interface FormState {
  section_name: string;
  html_content: string;
  status: boolean;
  imageFile: File | null;
}

const EMPTY_FORM: FormState = {
  section_name: "",
  html_content: "",
  status: true,
  imageFile: null,
};

export default function AboutPage() {
  const [existing, setExisting] = useState<About | null>(null);
  const [loading, setLoading] = useState(true);

  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [imagePreview, setImagePreview] = useState<string | null>(null);

  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const quillRef = useRef<any>(null);

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

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

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

        setExisting(item);

        if (item) {
          setForm({
            section_name: item.section_name ?? "",
            html_content: item.html_content ?? "",
            status: item.status ?? true,
            imageFile: null,
          });

          setImagePreview(item.image ?? null);
        } else {
          setForm(EMPTY_FORM);
          setImagePreview(null);
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0] || null;

    setForm((prev) => ({ ...prev, imageFile: file }));

    if (file) {
      setImagePreview(URL.createObjectURL(file));
    }
  };

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

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

    try {
      setSubmitting(true);

      const payload = new FormData();

      if (existing) payload.append("id", existing.id);
      payload.append("section_name", form.section_name.trim());
      payload.append("html_content", form.html_content);
      payload.append("status", String(form.status));

      if (form.imageFile) payload.append("image", form.imageFile);

      const response = await fetch("/api/admin/cms/about", {
        method: existing ? "PUT" : "POST",
        body: payload,
      });

      const result = await response.json();

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

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

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

      {loading ? (
        <CustomLoader />
      ) : (
        <div className="admin-form-section card">
          <div className="card-body">
            {error && <div className="alert alert-danger">{error}</div>}

            <div className="w-100">
              <div className="row gx-3">
                <div className="col-12 mb-3">
                  <label className="form-label">
                    Section Name <span className="text-danger">*</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="e.g. About 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">Image</label>

                  <input
                    type="file"
                    accept="image/*"
                    className="form-control"
                    onChange={handleImageChange}
                  />

                  {imagePreview && (
                    <div className="mt-2">
                      <Image
                        src={imagePreview}
                        alt="Preview"
                        width={160}
                        height={120}
                        className="rounded border"
                        style={{ objectFit: "cover" }}
                      />
                    </div>
                  )}
                </div>

                <div className="col-12 mb-3">
                  <label className="form-label">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/about/upload-image"
                    placeholder="Write the about content here..."
                  />
                  </div>
                </div>

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

                    <label className="form-check-label" htmlFor="aboutStatus">
                      {form.status ? "Active" : "Inactive"}
                    </label>
                  </div>
                </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>
      )}
    </div>
  );
}