"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { StatusToast } from "@/components/ui/status-toast";
import { SegmentEmailQualityFilters } from "@/components/segments/segment-email-quality-filters";
import { AiSegmentBuilderPanel } from "@/components/ai/ai-segment-builder-panel";
import {
  SegmentPreviewPanel,
  type SegmentPreviewConfig,
} from "@/components/segments/segment-preview-panel";
import type { EmailValidationStatus } from "@/lib/email-validation";
import {
  ensureDefaultEmailStatuses,
  resolveEmailStatusesFromFilters,
} from "@/lib/segment-email-filters";

type TargetType = "companies" | "people" | "contact_points" | "all";
type TargetChannel = "email" | "mobile" | "whatsapp" | "any";
type SegmentType = "dynamic" | "static";
type SegmentStatus = "active" | "inactive";

type FilterOptions = Record<string, unknown>;

interface SegmentFormProps {
  mode: "create" | "edit";
  initial?: {
    id?: string;
    name?: string;
    description?: string;
    targetType?: TargetType;
    targetChannel?: TargetChannel;
    type?: SegmentType;
    status?: SegmentStatus;
    filters?: Record<string, unknown>;
  };
}

const BOOL_OPTIONS = [
  { value: "", label: "أي" },
  { value: "true", label: "نعم" },
  { value: "false", label: "لا" },
];

export function SegmentForm({ mode, initial }: SegmentFormProps) {
  const router = useRouter();
  const [name, setName] = useState(initial?.name ?? "");
  const [description, setDescription] = useState(initial?.description ?? "");
  const [targetType, setTargetType] = useState<TargetType>(
    initial?.targetType ?? "companies"
  );
  const [targetChannel, setTargetChannel] = useState<TargetChannel>(
    (initial?.targetChannel as TargetChannel | undefined) ?? "any"
  );
  const [segmentType, setSegmentType] = useState<SegmentType>(
    initial?.type ?? "dynamic"
  );
  const [status, setStatus] = useState<SegmentStatus>(initial?.status ?? "active");
  const [filters, setFilters] = useState<Record<string, unknown>>(() =>
    ensureDefaultEmailStatuses(initial?.filters ?? {})
  );
  const [options, setOptions] = useState<FilterOptions | null>(null);
  const [previewConfig, setPreviewConfig] = useState<SegmentPreviewConfig | null>(
    null
  );
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState<{ message: string; variant: "success" | "error" } | null>(
    null
  );

  const loadOptions = useCallback(async () => {
    const res = await fetch(
      `/api/segments/filter-options?targetType=${targetType}`
    );
    if (res.ok) {
      const json = await res.json();
      setOptions(json.data ?? {});
    }
  }, [targetType]);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void loadOptions();
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [loadOptions]);

  const fields = useMemo(() => {
    if (targetType === "companies") {
      return [
        { key: "q", label: "بحث نصي", type: "text" as const },
        { key: "entityType", label: "نوع الكيان", type: "select", optionKey: "entityTypes" },
        { key: "sector", label: "القطاع", type: "select", optionKey: "sectors" },
        { key: "city", label: "المدينة", type: "select", optionKey: "cities" },
        { key: "priority", label: "الأولوية", type: "select", optionKey: "priorities" },
        {
          key: "dataConfidence",
          label: "الثقة",
          type: "select",
          optionKey: "confidenceLevels",
        },
        { key: "hasEmail", label: "لديه بريد", type: "bool" },
        { key: "hasMobile", label: "لديه جوال", type: "bool" },
        { key: "minLeadScore", label: "أقل Lead Score", type: "number" },
        {
          key: "recommendedService",
          label: "الخدمة المقترحة",
          type: "select",
          optionKey: "recommendedServices",
        },
      ];
    }
    if (targetType === "people") {
      return [
        { key: "q", label: "بحث نصي", type: "text" as const },
        { key: "jobTitle", label: "المسمى", type: "select", optionKey: "jobTitles" },
        {
          key: "seniorityLevel",
          label: "المستوى",
          type: "select",
          optionKey: "seniorityLevels",
        },
        {
          key: "isDecisionMaker",
          label: "صانع قرار",
          type: "select",
          optionKey: "decisionMakerValues",
        },
        { key: "companyId", label: "الشركة", type: "company" },
        { key: "hasEmail", label: "لديه بريد", type: "bool" },
        { key: "hasMobile", label: "لديه جوال", type: "bool" },
      ];
    }
    if (targetType === "contact_points") {
      return [
        { key: "q", label: "بحث نصي", type: "text" as const },
        { key: "contactType", label: "نوع الاتصال", type: "select", optionKey: "contactTypes" },
        { key: "entityType", label: "نوع الكيان", type: "select", optionKey: "entityTypes" },
        {
          key: "dataConfidence",
          label: "الثقة",
          type: "select",
          optionKey: "confidenceLevels",
        },
        { key: "isVerified", label: "موثق", type: "bool" },
      ];
    }
    return [
      { key: "q", label: "بحث نصي", type: "text" as const },
      { key: "sector", label: "القطاع", type: "select", optionKey: "sectors" },
      { key: "city", label: "المدينة", type: "select", optionKey: "cities" },
      { key: "entityType", label: "نوع الكيان", type: "select", optionKey: "entityTypes" },
      { key: "priority", label: "الأولوية", type: "select", optionKey: "priorities" },
      { key: "hasEmail", label: "لديه بريد", type: "bool" },
      { key: "hasMobile", label: "لديه جوال", type: "bool" },
      { key: "contactType", label: "نوع اتصال", type: "select", optionKey: "contactTypes" },
      { key: "jobTitle", label: "المسمى", type: "select", optionKey: "jobTitles" },
    ];
  }, [targetType]);

  const emailStatuses = resolveEmailStatusesFromFilters(filters);

  function setFilter(key: string, value: string) {
    setFilters((prev) => {
      const next = { ...prev };
      if (value === "") delete next[key];
      else if (value === "true") next[key] = true;
      else if (value === "false") next[key] = false;
      else if (key === "minLeadScore") next[key] = Number(value);
      else next[key] = value;
      return next;
    });
  }

  function setEmailStatuses(statuses: EmailValidationStatus[]) {
    setFilters((prev) => ({
      ...prev,
      emailStatuses: statuses,
    }));
  }

  function runPreview() {
    const normalizedFilters = ensureDefaultEmailStatuses(filters);
    setFilters(normalizedFilters);
    setPreviewConfig({
      targetType,
      targetChannel,
      filters: normalizedFilters,
    });
  }

  async function save() {
    if (saving) return;
    setSaving(true);
    const payload = {
      name,
      description,
      targetType,
      targetChannel,
      type: segmentType,
      status,
      filters:
        segmentType === "dynamic" ? ensureDefaultEmailStatuses(filters) : {},
      staticIds: segmentType === "static" ? [] : undefined,
    };
    const endpoint = mode === "create" ? "/api/segments" : `/api/segments/${initial?.id}`;
    const method = mode === "create" ? "POST" : "PATCH";
    const res = await fetch(endpoint, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    const json = await res.json();
    setSaving(false);
    if (!res.ok) {
      setToast({ message: json.error ?? "فشل الحفظ", variant: "error" });
      return;
    }
    setToast({ message: "تم حفظ الشريحة", variant: "success" });
    const id = json?.data?._id ?? initial?.id;
    router.push(id ? `/segments/${id}` : "/segments");
    router.refresh();
  }

  return (
    <div className="space-y-6">
      <StatusToast
        message={toast?.message ?? null}
        variant={toast?.variant}
        onDismiss={() => setToast(null)}
      />
      <section className="rounded-lg border border-neutral-200 bg-white p-5">
        <h1 className="mb-4 text-2xl font-bold">
          {mode === "create" ? "إنشاء شريحة" : "تعديل الشريحة"}
        </h1>
        <div className="grid gap-3 md:grid-cols-2">
          <input
            className="rounded border border-neutral-300 px-3 py-2 text-sm md:col-span-2"
            placeholder="اسم الشريحة"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
          <textarea
            className="rounded border border-neutral-300 px-3 py-2 text-sm md:col-span-2"
            placeholder="وصف"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
          <select
            value={targetType}
            onChange={(e) => {
              setTargetType(e.target.value as TargetType);
              setFilters(ensureDefaultEmailStatuses({}));
              setPreviewConfig(null);
            }}
            className="rounded border border-neutral-300 px-3 py-2 text-sm"
          >
            <option value="companies">شركات</option>
            <option value="people">أشخاص</option>
            <option value="contact_points">نقاط اتصال</option>
            <option value="all">الكل</option>
          </select>
          <select
            value={segmentType}
            onChange={(e) => setSegmentType(e.target.value as SegmentType)}
            className="rounded border border-neutral-300 px-3 py-2 text-sm"
          >
            <option value="dynamic">ديناميكية (فلاتر)</option>
            <option value="static">ثابتة (اختيار يدوي)</option>
          </select>
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value as SegmentStatus)}
            className="rounded border border-neutral-300 px-3 py-2 text-sm"
          >
            <option value="active">نشط</option>
            <option value="inactive">غير نشط</option>
          </select>
        </div>
      </section>

      {mode === "create" ? (
        <AiSegmentBuilderPanel
          onApply={({ filters: aiFilters, targetType: tt, targetChannel: tc }) => {
            setTargetType(tt as TargetType);
            setTargetChannel(tc as TargetChannel);
            setFilters(ensureDefaultEmailStatuses(aiFilters));
            setPreviewConfig(null);
            setToast({
              message: "تم تطبيق الفلاتر — راجع ثم احفظ الشريحة",
              variant: "success",
            });
          }}
        />
      ) : null}

      <section className="rounded-lg border border-neutral-200 bg-white p-5">
        <h2 className="mb-3 text-lg font-semibold">قناة التواصل</h2>
        <div className="flex flex-wrap gap-4 text-sm">
          {(
            [
              ["email", "البريد الإلكتروني"],
              ["mobile", "الجوال"],
              ["whatsapp", "واتساب"],
              ["any", "أي قناة"],
            ] as const
          ).map(([value, label]) => (
            <label key={value} className="inline-flex items-center gap-2">
              <input
                type="radio"
                name="targetChannel"
                checked={targetChannel === value}
                onChange={() => setTargetChannel(value)}
              />
              {label}
            </label>
          ))}
        </div>
      </section>

      {segmentType === "dynamic" ? (
        <section className="rounded-lg border border-neutral-200 bg-white p-5">
          <h2 className="mb-3 text-lg font-semibold">جودة البريد</h2>
          <SegmentEmailQualityFilters
            selected={emailStatuses}
            onChange={setEmailStatuses}
          />
        </section>
      ) : null}

      {segmentType === "dynamic" ? (
        <section className="rounded-lg border border-neutral-200 bg-white p-5">
          <h2 className="mb-3 text-lg font-semibold">الفلاتر</h2>
          <div className="grid gap-3 md:grid-cols-2">
            {fields.map((field) => {
              if (field.type === "text" || field.type === "number") {
                return (
                  <input
                    key={field.key}
                    type={field.type === "number" ? "number" : "text"}
                    className="rounded border border-neutral-300 px-3 py-2 text-sm"
                    placeholder={field.label}
                    value={String(filters[field.key] ?? "")}
                    onChange={(e) => setFilter(field.key, e.target.value)}
                  />
                );
              }
              if (field.type === "bool") {
                return (
                  <label key={field.key} className="block text-sm">
                    {field.label}
                    <select
                      className="mt-1 w-full rounded border px-3 py-2 text-sm"
                      value={
                        filters[field.key] === true
                          ? "true"
                          : filters[field.key] === false
                            ? "false"
                            : ""
                      }
                      onChange={(e) => setFilter(field.key, e.target.value)}
                    >
                      {BOOL_OPTIONS.map((o) => (
                        <option key={o.value} value={o.value}>
                          {o.label}
                        </option>
                      ))}
                    </select>
                  </label>
                );
              }
              if (field.type === "company") {
                const companies =
                  (options?.companies as Array<{ _id: string; name: string }>) ?? [];
                return (
                  <label key={field.key} className="block text-sm">
                    {field.label}
                    <select
                      className="mt-1 w-full rounded border px-3 py-2 text-sm"
                      value={String(filters.companyId ?? "")}
                      onChange={(e) => setFilter("companyId", e.target.value)}
                    >
                      <option value="">أي شركة</option>
                      {companies.map((c) => (
                        <option key={c._id} value={c._id}>
                          {c.name}
                        </option>
                      ))}
                    </select>
                  </label>
                );
              }
              const list =
                (options?.[field.optionKey ?? ""] as string[] | undefined) ?? [];
              return (
                <label key={field.key} className="block text-sm">
                  {field.label}
                  <select
                    className="mt-1 w-full rounded border px-3 py-2 text-sm"
                    value={String(filters[field.key] ?? "")}
                    onChange={(e) => setFilter(field.key, e.target.value)}
                  >
                    <option value="">أي</option>
                    {list.map((v) => (
                      <option key={v} value={v}>
                        {v}
                      </option>
                    ))}
                  </select>
                </label>
              );
            })}
          </div>
        </section>
      ) : (
        <section className="rounded-lg border border-neutral-200 bg-white p-5 text-sm text-neutral-600">
          <p>
            الشريحة الثابتة: بعد الحفظ أضف الأعضاء من صفحة تفاصيل الشريحة، أو من جداول
            السوق (تحديد + إضافة إلى شريحة).
          </p>
        </section>
      )}

      <div className="flex flex-wrap gap-2">
        {segmentType === "dynamic" ? (
          <button
            type="button"
            onClick={runPreview}
            className="inline-flex items-center gap-2 rounded bg-neutral-800 px-4 py-2 text-sm text-white"
          >
            معاينة
          </button>
        ) : null}
        <button
          type="button"
          onClick={() => void save()}
          disabled={saving || !name.trim()}
          className="inline-flex items-center gap-2 rounded bg-[var(--accent)] px-4 py-2 text-sm text-white disabled:opacity-50"
        >
          {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          {saving ? "جاري الحفظ..." : "حفظ"}
        </button>
      </div>

      {previewConfig ? (
        <SegmentPreviewPanel
          key={JSON.stringify(previewConfig)}
          config={previewConfig}
          onError={(message) => setToast({ message, variant: "error" })}
        />
      ) : null}
    </div>
  );
}
