"use client";

import { useEffect, useState } from "react";
import { useApi } from "@/lib/useApi";

type Merchant = {
  id: number;
  name: string;
};

type CategoryMapping = {
  id: number;
  merchantId: number;
  merchantName: string;
  rawCategoryPath: string;
  partCategoryId: number | null;
  partCategoryName?: string | null;
};

// Matches the Spring MerchantCategoryMappingDto record
type MerchantCategoryMappingDto = {
  id: number;
  merchantId: number;
  merchantName: string;
  rawCategoryPath: string;
  partCategoryId: number | null;
  partCategoryName?: string | null;
};

export default function MerchantCategoryMappingPage() {
  const { get, post } = useApi();

  const [merchants, setMerchants] = useState<Merchant[]>([]);
  const [selectedMerchantId, setSelectedMerchantId] = useState<number | null>(
    null
  );
  const [mappings, setMappings] = useState<CategoryMapping[]>([]);
  const [loadingMerchants, setLoadingMerchants] = useState(false);
  const [loadingMappings, setLoadingMappings] = useState(false);
  const [savingId, setSavingId] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 1) Load merchants for the dropdown
  useEffect(() => {
    setLoadingMerchants(true);
    setError(null);

    get<Merchant[]>("/api/admin/category-mappings/merchants")
      .then((data) => {
        setMerchants(data);
        if (data.length > 0 && selectedMerchantId == null) {
          setSelectedMerchantId(data[0].id);
        }
      })
      .catch((err: any) => {
        console.error("Failed to load merchants", err);
        setError(
          err instanceof Error ? err.message : "Failed to load merchants"
        );
      })
      .finally(() => setLoadingMerchants(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 2) Load mappings when merchant changes (THIS sends merchantId)
  useEffect(() => {
    if (selectedMerchantId == null) return;

    setLoadingMappings(true);
    setError(null);

    get<CategoryMapping[]>(
      `/api/admin/category-mappings?merchantId=${selectedMerchantId}`
    )
      .then((data) => {
        setMappings(data);
      })
      .catch((err: any) => {
        console.error("Failed to load category mappings", err);
        setError(
          err instanceof Error ? err.message : "Failed to load category mappings"
        );
      })
      .finally(() => setLoadingMappings(false));
  }, [selectedMerchantId]);

  // 3) Save a single mapping row (adjust endpoint if yours differs)
  const handleSaveMapping = async (
    mappingId: number,
    updated: { partCategoryId: number | null }
  ) => {
    setSavingId(mappingId);
    setError(null);
    try {
      const updatedMapping = await post<MerchantCategoryMappingDto>(
        `/api/admin/category-mappings/${mappingId}`,
        {
          partCategoryId: updated.partCategoryId,
        }
      );
  
      setMappings((prev) =>
        prev.map((m) => (m.id === mappingId ? {
          ...m,
          // map Java DTO fields back into your UI model
          merchantId: updatedMapping.merchantId,
          merchantName: updatedMapping.merchantName,
          rawCategoryPath: updatedMapping.rawCategoryPath,
          partCategoryId: updatedMapping.partCategoryId,
          partCategoryName: updatedMapping.partCategoryName,
        } : m))
      );
    } catch (err: any) {
      console.error("Failed to save mapping", err);
      setError(
        err instanceof Error ? err.message : "Failed to save mapping"
      );
    } finally {
      setSavingId(null);
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-zinc-50">
          Merchant Category Mapping
        </h1>

        <div className="flex items-center gap-2">
          <span className="text-sm text-zinc-400">Merchant:</span>
          <select
            className="bg-zinc-900 border border-zinc-700 rounded px-2 py-1 text-sm"
            value={selectedMerchantId ?? ""}
            onChange={(e) =>
              setSelectedMerchantId(
                e.target.value ? Number(e.target.value) : null
              )
            }
          >
            {loadingMerchants && (
              <option value="">Loading merchants…</option>
            )}
            {!loadingMerchants && merchants.length === 0 && (
              <option value="">No merchants</option>
            )}
            {merchants.map((m) => (
              <option key={m.id} value={m.id}>
                {m.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      {error && (
        <div className="rounded bg-red-900/40 border border-red-700 px-3 py-2 text-sm text-red-200">
          {error}
        </div>
      )}

      <div className="border border-zinc-800 rounded-lg overflow-hidden">
        <div className="bg-zinc-900 border-b border-zinc-800 px-4 py-2 text-xs uppercase tracking-wide text-zinc-400">
          Category Mappings
        </div>

        {loadingMappings ? (
          <div className="p-4 text-sm text-zinc-400">Loading mappings…</div>
        ) : mappings.length === 0 ? (
          <div className="p-4 text-sm text-zinc-400">
            No mappings found for this merchant.
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-zinc-950/60 border-b border-zinc-800">
              <tr>
                <th className="text-left px-4 py-2 text-xs uppercase tracking-wide text-zinc-500">
                  Merchant Category
                </th>
                <th className="text-left px-4 py-2 text-xs uppercase tracking-wide text-zinc-500">
                  Global Category
                </th>
                <th className="px-4 py-2 text-xs uppercase tracking-wide text-zinc-500">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody>
              {mappings.map((m) => (
                <tr key={m.id} className="border-t border-zinc-800">
                  <td className="px-4 py-2 text-zinc-100">
                    {m.rawCategoryPath}
                  </td>
                  <td className="px-4 py-2">
                    {/* For now, simple text input for partCategoryId.
                        You can swap this for a select populated from /api/admin/categories */}
                    <input
                      type="number"
                      className="bg-zinc-950 border border-zinc-700 rounded px-2 py-1 text-sm w-28"
                      value={m.partCategoryId ?? ""}
                      onChange={(e) => {
                        const value = e.target.value
                          ? Number(e.target.value)
                          : null;
                        setMappings((prev) =>
                          prev.map((row) =>
                            row.id === m.id
                              ? { ...row, partCategoryId: value }
                              : row
                          )
                        );
                      }}
                    />
                    {m.partCategoryName && (
                      <div className="text-xs text-zinc-500 mt-1">
                        {m.partCategoryName}
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-2 text-right">
                    <button
                      onClick={() =>
                        handleSaveMapping(m.id, {
                          partCategoryId: m.partCategoryId ?? null,
                        })
                      }
                      disabled={savingId === m.id}
                      className="text-xs px-3 py-1 rounded border border-zinc-600 hover:bg-zinc-800 disabled:opacity-50"
                    >
                      {savingId === m.id ? "Saving…" : "Save"}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}