"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";

type SegmentOption = { _id: string; name: string };

type AddToSegmentModalProps = {
  targetType: "companies" | "people" | "contact_points";
  selectedIds: string[];
  onClose: () => void;
  onSuccess: () => void;
};

export function AddToSegmentModal({
  targetType,
  selectedIds,
  onClose,
  onSuccess,
}: AddToSegmentModalProps) {
  const [segments, setSegments] = useState<SegmentOption[]>([]);
  const [segmentId, setSegmentId] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    const res = await fetch(`/api/segments/static-list?targetType=${targetType}`);
    const json = (await res.json()) as { data?: SegmentOption[] };
    setSegments(json.data ?? []);
  }, [targetType]);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void load();
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [load]);

  async function submit() {
    if (!segmentId) {
      setError("اختر شريحة");
      return;
    }
    setLoading(true);
    setError("");
    const res = await fetch(`/api/segments/${segmentId}/members`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ids: selectedIds }),
    });
    const json = (await res.json()) as { error?: string };
    setLoading(false);
    if (!res.ok) {
      setError(json.error ?? "فشل الإضافة");
      return;
    }
    onSuccess();
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="w-full max-w-md rounded-lg bg-white p-5 shadow-lg">
        <h3 className="text-lg font-semibold">إضافة إلى شريحة ثابتة</h3>
        <p className="mt-1 text-sm text-neutral-600">
          {selectedIds.length} عنصر محدد
        </p>
        {segments.length === 0 ? (
          <p className="mt-3 text-sm text-amber-700">
            لا توجد شرائح ثابتة لهذا النوع.{" "}
            <Link href="/segments/new" className="text-[var(--accent)] underline">
              أنشئ شريحة ثابتة
            </Link>
          </p>
        ) : (
          <select
            className="mt-3 w-full rounded border px-3 py-2 text-sm"
            value={segmentId}
            onChange={(e) => setSegmentId(e.target.value)}
          >
            <option value="">— اختر شريحة —</option>
            {segments.map((s) => (
              <option key={s._id} value={s._id}>
                {s.name}
              </option>
            ))}
          </select>
        )}
        {error ? <p className="mt-2 text-sm text-red-600">{error}</p> : null}
        <div className="mt-4 flex justify-end gap-2">
          <button type="button" onClick={onClose} className="rounded border px-3 py-1 text-sm">
            إلغاء
          </button>
          <button
            type="button"
            disabled={loading || segments.length === 0}
            onClick={() => void submit()}
            className="rounded bg-[var(--accent)] px-3 py-1 text-sm text-white disabled:opacity-50"
          >
            {loading ? "جاري الإضافة..." : "إضافة"}
          </button>
        </div>
      </div>
    </div>
  );
}
