"use client";

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

interface FooterBadge {
  id: string;
  title: string;
  description?: string | null;
  image?: string | null;
  sort_order?: number | null;
  status?: boolean | null;
  created_at?: string | null;
}

interface FormState {
  title: string;
  description: string;
  sort_order: string;
  status: boolean;
  imageFile: File | null;
}

const EMPTY_FORM: FormState = {
  title: "",
  description: "",
  sort_order: "0",
  status: true,
  imageFile: null,
};

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

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

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

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

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

  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);
    setImagePreview(null);
    setError(null);
    setShowForm(true);
  };

  const handleEdit = (badge: FooterBadge) => {
    setEditingId(badge.id);

    setForm({
      title: badge.title,
      description: badge.description ?? "",
      sort_order: String(badge.sort_order ?? 0),
      status: badge.status ?? true,
      imageFile: null,
    });

    setImagePreview(badge.image ?? null);
    setError(null);
    setShowForm(true);
  };

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

  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 handleDelete = async (id: string) => {
    const confirmed = window.confirm(
      "Are you sure you want to delete this footer badge?"
    );

    if (!confirmed) return;

    try {
      const response = await fetch(
        `/api/admin/cms/footer-badge?id=${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 footer badge");
      }
    } catch (error) {
      console.error(error);
      alert("Something went wrong");
    }
  };

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

    if (!form.title.trim()) {
      setError("Title is required.");
      return;
    }

    try {
      setSubmitting(true);

      const payload = new FormData();

      if (editingId) payload.append("id", editingId);
      payload.append("title", form.title.trim());
      payload.append("description", form.description.trim());
      payload.append("sort_order", form.sort_order || "0");
      payload.append("status", String(form.status));

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

      const response = await fetch("/api/admin/cms/footer-badge", {
        method: editingId ? "PUT" : "POST",
        body: payload,
      });

      const result = await response.json();

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

      await fetchBadges();

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

  const columns = useMemo<ColumnDef<FooterBadge>[]>(
    () => [
      {
        accessorKey: "image",
        header: "Image",
        cell: ({ getValue }) => {
          const value = getValue() as string | null;

          if (!value)
            return <span className="text-muted">No image</span>;

          return (
            <Image
              src={value}
              alt="badge"
              width={50}
              height={50}
              className="rounded"
              style={{ objectFit: "cover" }}
            />
          );
        },
      },
      {
        accessorKey: "title",
        header: "Title",
      },
    //   {
    //     accessorKey: "description",
    //     header: "Description",
    //     cell: ({ getValue }) => {
    //       const value = (getValue() as string) || "";

    //       return (
    //         <span className="text-muted">
    //           {value.length > 80 ? `${value.substring(0, 80)}...` : value}
    //         </span>
    //       );
    //     },
    //   },
      {
        accessorKey: "sort_order",
        header: "Sort Order",
      },
      {
        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 badge = row.original;

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

              <button
                className="btn btn-danger btn-sm table-action-btn"
                onClick={() => handleDelete(badge.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">Footer Badges</h2>
            <p className="admin-page-subtitle">
              Manage the footer badge cards (image + text)
            </p>
          </div>

          <button className="admin-theme-btn" onClick={handleAddNew}>
            + Add New Badge
          </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 Footer Badge
                      </>
                    ) : (
                      <>
                        <i className="bi bi-plus-circle me-2 text-primary" />
                        Add New Footer Badge
                      </>
                    )}
                  </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">
                        Title <span className="text-danger">*</span>
                      </label>

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

                    {/* <div className="col-12">
                      <label className="form-label">Description</label>

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

                    <div className="col-md-6">
                      <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={80}
                            height={80}
                            className="rounded border"
                            style={{ objectFit: "cover" }}
                          />
                        </div>
                      )}
                    </div>

                    <div className="col-md-6">
                      <label className="form-label">Sort Order</label>

                      <input
                        type="number"
                        className="form-control"
                        placeholder="0"
                        value={form.sort_order}
                        onChange={(e) =>
                          setForm((prev) => ({
                            ...prev,
                            sort_order: e.target.value,
                          }))
                        }
                        min={0}
                      />
                    </div>

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

                        <label
                          className="form-check-label"
                          htmlFor="badgeStatus"
                        >
                          {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 Badge
                      </>
                    ) : (
                      <>
                        <i className="bi bi-plus-circle me-1" /> Add Badge
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>

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