"use client";

import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import CustomLoader from "@/components/common/CustomLoader";

interface WhyRKDAItem {
  id: string;
  title: string;
  description: string;
  icon: string;
  sort_order: number;
  status: boolean;
  iconFile?: File | null;
}

export default function WhyRKDAPage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const [items, setItems] = useState<WhyRKDAItem[]>([]);

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

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

      const res = await fetch("/api/admin/cms/why-rkda");
      const json = await res.json();

      if (json.success) {
        setItems(
          json.data.map((item: any) => ({
            ...item,
            iconFile: null,
          }))
        );
      }
    } catch {
      toast.error("Failed to load data");
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (
    index: number,
    field: string,
    value: any
  ) => {
    const updated = [...items];

    updated[index] = {
      ...updated[index],
      [field]: value,
    };

    setItems(updated);
  };

  const handleFileChange = (
    index: number,
    file: File
  ) => {
    const updated = [...items];

    updated[index].iconFile = file;
    updated[index].icon = URL.createObjectURL(file);

    setItems(updated);
  };

  const handleSave = async () => {
    try {
      setSaving(true);

      for (const item of items) {
        const formData = new FormData();

        formData.append("id", item.id);
        formData.append("title", item.title);
        formData.append(
          "description",
          item.description || ""
        );
        formData.append(
          "sort_order",
          String(item.sort_order)
        );
        formData.append(
          "status",
          String(item.status)
        );

        if (item.iconFile) {
          formData.append(
            "icon",
            item.iconFile
          );
        }

        await fetch("/api/admin/cms/why-rkda", {
          method: "PUT",
          body: formData,
        });
      }

      toast.success(
        "Why RKDA updated successfully"
      );

      fetchData();
    } catch {
      toast.error("Failed to save changes");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <CustomLoader />;
  }

  return (
    <div className="admin-page-wrapper">
      <div className="admin-page-header mb-4">
        <div className="d-flex justify-content-between align-items-center">
          <div>
            <h2 className="admin-page-title">
              Why RKDA
            </h2>

            <p className="admin-page-subtitle">
              Manage Why RKDA section
            </p>
          </div>

          <button
            className="admin-theme-btn"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? (
              <>
                <span className="spinner-border spinner-border-sm me-2" />
                Saving...
              </>
            ) : (
              <>
                <i className="bi bi-floppy me-2" />
                Save Changes
              </>
            )}
          </button>
        </div>
      </div>

      <div className="row g-4">
        {items.map((item, index) => (
          <div
            className="col-lg-12"
            key={item.id}
          >
            <div className="card-theme p-4 h-100">
              <h5 className="mb-3 fw-semibold">
                <i className="bi bi-award me-2 text-primary" />
                Card {index + 1}
              </h5>

              <div className="row g-3">
                <div className="col-8">
                  <label className="form-label">
                    Title
                  </label>

                  <input
                    type="text"
                    className="form-control"
                    value={item.title}
                    onChange={(e) =>
                      handleChange(
                        index,
                        "title",
                        e.target.value
                      )
                    }
                  />
                </div>
                <div className="col-md-4 d-flex align-items-center">
                  <div className="form-check form-switch mt-4">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      checked={item.status}
                      onChange={(e) =>
                        handleChange(
                          index,
                          "status",
                          e.target.checked
                        )
                      }
                    />

                    <label className="form-check-label">
                      Active
                    </label>
                  </div>
                </div>

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

                  <textarea
                    rows={2}
                    className="form-control"
                    value={
                      item.description || ""
                    }
                    onChange={(e) =>
                      handleChange(
                        index,
                        "description",
                        e.target.value
                      )
                    }
                  />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-4 text-end">
        <button
          className="admin-theme-btn"
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? (
            <>
              <span className="spinner-border spinner-border-sm me-2" />
              Saving...
            </>
          ) : (
            <>
              <i className="bi bi-floppy me-2" />
              Save Changes
            </>
          )}
        </button>
      </div>
    </div>
  );
}