"use client";

import { useState, useCallback } from "react";
import { X, Loader2 } from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

interface CreateLeadModalProps {
  isAr: boolean;
  onClose: () => void;
  onCreated: () => void;
}

export default function CreateLeadModal({
  isAr,
  onClose,
  onCreated,
}: CreateLeadModalProps) {
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    company: "",
    source: "MANUAL",
    dealValue: "",
    dealCurrency: "QAR",
    tags: "",
  });
  const [saving, setSaving] = useState(false);

  const handleSubmit = useCallback(async () => {
    if (!form.name.trim()) return;
    setSaving(true);
    try {
      const payload = {
        name: form.name,
        email: form.email || undefined,
        phone: form.phone || undefined,
        company: form.company || undefined,
        source: form.source,
        dealValue: form.dealValue ? parseFloat(form.dealValue) : undefined,
        dealCurrency: form.dealCurrency,
        tags: form.tags
          ? form.tags
              .split(",")
              .map((t) => t.trim())
              .filter(Boolean)
          : undefined,
      };
      const res = await fetchWithCSRF("/api/leads", {
        method: "POST",
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        onCreated();
        onClose();
      }
    } catch {
      // silent
    } finally {
      setSaving(false);
    }
  }, [form, onCreated, onClose]);

  const sourceOptions = [
    { value: "MANUAL", en: "Manual", ar: "يدوي" },
    { value: "WHATSAPP", en: "WhatsApp", ar: "واتساب" },
    { value: "WEBSITE", en: "Website", ar: "موقع إلكتروني" },
    { value: "REFERRAL", en: "Referral", ar: "إحالة" },
    { value: "SOCIAL", en: "Social Media", ar: "وسائل التواصل" },
    { value: "VOICE", en: "Voice Call", ar: "مكالمة صوتية" },
  ];

  return (
    <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200">
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "إضافة عميل محتمل" : "Add New Lead"}
          </h3>
          <button
            onClick={onClose}
            className="p-1.5 rounded-lg hover:bg-slate-100 transition-colors"
          >
            <X className="h-5 w-5 text-slate-500" />
          </button>
        </div>

        {/* Form */}
        <div className="p-6 space-y-4">
          <div>
            <label className="text-xs font-medium text-slate-600 mb-1 block">
              {isAr ? "الاسم *" : "Name *"}
            </label>
            <input
              value={form.name}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, name: e.target.value }))
              }
              placeholder={isAr ? "اسم العميل" : "Lead name"}
              className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              dir={isAr ? "rtl" : "ltr"}
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "البريد الإلكتروني" : "Email"}
              </label>
              <input
                type="email"
                value={form.email}
                onChange={(e) =>
                  setForm((prev) => ({ ...prev, email: e.target.value }))
                }
                placeholder="email@example.com"
                className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              />
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "الهاتف" : "Phone"}
              </label>
              <input
                type="tel"
                value={form.phone}
                onChange={(e) =>
                  setForm((prev) => ({ ...prev, phone: e.target.value }))
                }
                placeholder="+974..."
                className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              />
            </div>
          </div>

          <div>
            <label className="text-xs font-medium text-slate-600 mb-1 block">
              {isAr ? "الشركة" : "Company"}
            </label>
            <input
              value={form.company}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, company: e.target.value }))
              }
              placeholder={isAr ? "اسم الشركة" : "Company name"}
              className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              dir={isAr ? "rtl" : "ltr"}
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "المصدر" : "Source"}
              </label>
              <select
                value={form.source}
                onChange={(e) =>
                  setForm((prev) => ({ ...prev, source: e.target.value }))
                }
                className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              >
                {sourceOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {isAr ? opt.ar : opt.en}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "قيمة الصفقة" : "Deal Value"}
              </label>
              <div className="flex gap-1.5">
                <select
                  value={form.dealCurrency}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      dealCurrency: e.target.value,
                    }))
                  }
                  className="px-2 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200 w-20"
                >
                  <option value="QAR">QAR</option>
                  <option value="SAR">SAR</option>
                  <option value="AED">AED</option>
                  <option value="USD">USD</option>
                </select>
                <input
                  type="number"
                  value={form.dealValue}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      dealValue: e.target.value,
                    }))
                  }
                  placeholder="0"
                  className="flex-1 px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
                />
              </div>
            </div>
          </div>

          <div>
            <label className="text-xs font-medium text-slate-600 mb-1 block">
              {isAr ? "العلامات (مفصولة بفاصلة)" : "Tags (comma separated)"}
            </label>
            <input
              value={form.tags}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, tags: e.target.value }))
              }
              placeholder={isAr ? "VIP, عاجل" : "VIP, urgent"}
              className="w-full px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              dir={isAr ? "rtl" : "ltr"}
            />
          </div>
        </div>

        {/* Footer */}
        <div className="flex gap-2 justify-end px-6 py-4 border-t border-slate-200">
          <button
            onClick={onClose}
            className="px-4 py-2.5 text-sm text-slate-600 hover:bg-slate-100 rounded-xl transition-colors"
          >
            {isAr ? "إلغاء" : "Cancel"}
          </button>
          <button
            onClick={handleSubmit}
            disabled={!form.name.trim() || saving}
            className="px-4 py-2.5 bg-indigo-600 text-white text-sm rounded-xl hover:bg-indigo-700 disabled:opacity-50 transition-colors flex items-center gap-1.5"
          >
            {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
            {isAr ? "إنشاء العميل" : "Create Lead"}
          </button>
        </div>
      </div>
    </div>
  );
}
