"use client";

import { useCallback, useEffect, useState } from "react";

type ImportSettings = {
  duplicateThreshold: number;
  companyMatchFields: string[];
  personMatchFields: string[];
  contactMatchFields: string[];
  autoDuplicateDetection: boolean;
  autoDataQualityChecks: boolean;
};

function fieldsToText(fields: string[]) {
  return fields.join(", ");
}

function textToFields(text: string) {
  return text
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);
}

export function ImportsSettingsClient() {
  const [form, setForm] = useState<ImportSettings>({
    duplicateThreshold: 0.85,
    companyMatchFields: [],
    personMatchFields: [],
    contactMatchFields: [],
    autoDuplicateDetection: true,
    autoDataQualityChecks: true,
  });
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/settings/imports");
    const json = (await res.json()) as { data?: ImportSettings; error?: string };
    if (!res.ok) {
      setError(json.error ?? "Failed to load");
    } else if (json.data) {
      setForm(json.data);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void load();
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [load]);

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setMessage("");
    const res = await fetch("/api/settings/imports", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    const json = (await res.json()) as { error?: string };
    if (!res.ok) {
      setError(json.error ?? "Save failed");
      return;
    }
    setMessage("Import settings saved");
    void load();
  }

  if (loading) return <p className="text-sm text-neutral-500">جاري التحميل...</p>;

  return (
    <div className="space-y-4">
      <header>
        <h1 className="text-xl font-bold">إعدادات الاستيراد</h1>
        <p className="text-sm text-neutral-500">Imports — deduplication &amp; quality</p>
      </header>
      {error ? <p className="text-sm text-red-600">{error}</p> : null}
      {message ? <p className="text-sm text-green-700">{message}</p> : null}
      <form onSubmit={(e) => void save(e)} className="grid max-w-lg gap-3 rounded border bg-white p-4">
        <label className="block text-sm">
          Duplicate threshold (0–1)
          <input
            type="number"
            step="0.01"
            min={0}
            max={1}
            className="mt-1 w-full rounded border px-3 py-2"
            value={form.duplicateThreshold}
            onChange={(e) =>
              setForm({ ...form, duplicateThreshold: Number(e.target.value) })
            }
          />
        </label>
        <label className="block text-sm">
          Company match fields (comma-separated)
          <input
            className="mt-1 w-full rounded border px-3 py-2"
            value={fieldsToText(form.companyMatchFields)}
            onChange={(e) =>
              setForm({ ...form, companyMatchFields: textToFields(e.target.value) })
            }
          />
        </label>
        <label className="block text-sm">
          Person match fields
          <input
            className="mt-1 w-full rounded border px-3 py-2"
            value={fieldsToText(form.personMatchFields)}
            onChange={(e) =>
              setForm({ ...form, personMatchFields: textToFields(e.target.value) })
            }
          />
        </label>
        <label className="block text-sm">
          Contact match fields
          <input
            className="mt-1 w-full rounded border px-3 py-2"
            value={fieldsToText(form.contactMatchFields)}
            onChange={(e) =>
              setForm({ ...form, contactMatchFields: textToFields(e.target.value) })
            }
          />
        </label>
        <p className="text-xs text-neutral-500 md:col-span-2">
          Duplicate and data-quality review are handled in GPT preprocessing before import; CRM
          no longer creates review records on import.
        </p>
        <button type="submit" className="rounded bg-[var(--accent)] px-3 py-2 text-sm text-white">
          حفظ
        </button>
      </form>
    </div>
  );
}
