"use client";

import { useState, useCallback } from "react";
import {
  Plus,
  Loader2,
  Copy,
  Trash2,
  Eye,
  Globe,
  MessageSquare,
  FileText,
} from "lucide-react";
import type { CaptureFormOutput } from "@/lib/types/lead-crm.types";

interface CaptureFormsManagerProps {
  isAr: boolean;
  forms: CaptureFormOutput[];
  onRefresh: () => void;
}

export default function CaptureFormsManager({
  isAr,
  forms,
  onRefresh,
}: CaptureFormsManagerProps) {
  const [creating, setCreating] = useState(false);
  const [showCreate, setShowCreate] = useState(false);
  const [newForm, setNewForm] = useState({
    name: "",
    formType: "EMBEDDED" as string,
    fields: [
      {
        name: "name",
        type: "text",
        labelEn: "Full Name",
        labelAr: "الاسم الكامل",
        required: true,
      },
      {
        name: "email",
        type: "email",
        labelEn: "Email",
        labelAr: "البريد الإلكتروني",
        required: true,
      },
      {
        name: "phone",
        type: "tel",
        labelEn: "Phone",
        labelAr: "الهاتف",
        required: false,
      },
    ],
  });

  const handleCreate = useCallback(async () => {
    if (!newForm.name.trim()) return;
    setCreating(true);
    try {
      const res = await fetch("/api/leads/capture-forms", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newForm),
      });
      if (res.ok) {
        setShowCreate(false);
        setNewForm((prev) => ({ ...prev, name: "" }));
        onRefresh();
      }
    } catch {
      // silent
    } finally {
      setCreating(false);
    }
  }, [newForm, onRefresh]);

  const handleDelete = useCallback(
    async (formId: string) => {
      try {
        await fetch(`/api/leads/capture-forms/${formId}`, {
          method: "DELETE",
        });
        onRefresh();
      } catch {
        // silent
      }
    },
    [onRefresh],
  );

  const handleCopyEmbed = useCallback(async (formId: string) => {
    try {
      const res = await fetch(`/api/leads/capture-forms/${formId}/embed`);
      if (res.ok) {
        const json = await res.json();
        await navigator.clipboard.writeText(json.data?.embedCode || "");
      }
    } catch {
      // silent
    }
  }, []);

  const formTypeIcons: Record<string, React.ReactNode> = {
    EMBEDDED: <Globe className="h-4 w-4" />,
    POPUP: <Eye className="h-4 w-4" />,
    WHATSAPP: <MessageSquare className="h-4 w-4" />,
    LANDING_PAGE: <FileText className="h-4 w-4" />,
  };

  const formTypeLabels: Record<string, { en: string; ar: string }> = {
    EMBEDDED: { en: "Embedded", ar: "مضمّن" },
    POPUP: { en: "Popup", ar: "منبثق" },
    WHATSAPP: { en: "WhatsApp", ar: "واتساب" },
    LANDING_PAGE: { en: "Landing Page", ar: "صفحة هبوط" },
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "نماذج الالتقاط" : "Capture Forms"}
          </h3>
          <p className="text-sm text-slate-500">
            {isAr
              ? "أنشئ نماذج لالتقاط العملاء المحتملين"
              : "Create forms to capture leads from your website"}
          </p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-1.5 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 transition-colors"
        >
          <Plus className="h-4 w-4" />
          {isAr ? "نموذج جديد" : "New Form"}
        </button>
      </div>

      {/* Create form panel */}
      {showCreate && (
        <div className="bg-white rounded-2xl border border-slate-200 p-5 space-y-4">
          <h4 className="text-sm font-semibold text-slate-900">
            {isAr ? "نموذج التقاط جديد" : "New Capture Form"}
          </h4>
          <div className="space-y-3">
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "اسم النموذج" : "Form Name"}
              </label>
              <input
                value={newForm.name}
                onChange={(e) =>
                  setNewForm((prev) => ({ ...prev, name: e.target.value }))
                }
                placeholder={isAr ? "مثال: نموذج الاتصال" : "e.g. Contact Form"}
                className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
                dir={isAr ? "rtl" : "ltr"}
              />
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "نوع النموذج" : "Form Type"}
              </label>
              <div className="flex gap-2 flex-wrap">
                {Object.entries(formTypeLabels).map(([key, label]) => (
                  <button
                    key={key}
                    onClick={() =>
                      setNewForm((prev) => ({ ...prev, formType: key }))
                    }
                    className={`flex items-center gap-1.5 px-3 py-2 text-sm rounded-xl border transition-colors ${
                      newForm.formType === key
                        ? "border-indigo-300 bg-indigo-50 text-indigo-700"
                        : "border-slate-200 text-slate-600 hover:bg-slate-50"
                    }`}
                  >
                    {formTypeIcons[key]}
                    {isAr ? label.ar : label.en}
                  </button>
                ))}
              </div>
            </div>
          </div>
          <div className="flex gap-2 justify-end">
            <button
              onClick={() => setShowCreate(false)}
              className="px-4 py-2 text-sm text-slate-600 hover:bg-slate-100 rounded-xl transition-colors"
            >
              {isAr ? "إلغاء" : "Cancel"}
            </button>
            <button
              onClick={handleCreate}
              disabled={!newForm.name.trim() || creating}
              className="px-4 py-2 bg-indigo-600 text-white text-sm rounded-xl hover:bg-indigo-700 disabled:opacity-50 transition-colors flex items-center gap-1.5"
            >
              {creating && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
              {isAr ? "إنشاء" : "Create"}
            </button>
          </div>
        </div>
      )}

      {/* Forms list */}
      {forms.length === 0 ? (
        <div className="text-center py-16 text-slate-400">
          <FileText className="h-10 w-10 mx-auto mb-3 opacity-50" />
          <p className="text-sm">
            {isAr
              ? "لا توجد نماذج التقاط. أنشئ واحداً لبدء جمع العملاء المحتملين."
              : "No capture forms yet. Create one to start collecting leads."}
          </p>
        </div>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2">
          {forms.map((form) => (
            <div
              key={form.id}
              className="bg-white rounded-2xl border border-slate-200 p-4 hover:shadow-md transition-shadow"
            >
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-2">
                  <div className="w-9 h-9 rounded-xl bg-indigo-100 flex items-center justify-center text-indigo-600">
                    {formTypeIcons[form.formType] || (
                      <FileText className="h-4 w-4" />
                    )}
                  </div>
                  <div>
                    <h4 className="text-sm font-semibold text-slate-900">
                      {form.name}
                    </h4>
                    <p className="text-xs text-slate-500">
                      {isAr
                        ? formTypeLabels[form.formType]?.ar || form.formType
                        : formTypeLabels[form.formType]?.en || form.formType}
                    </p>
                  </div>
                </div>
                <span
                  className={`text-[10px] px-2 py-0.5 rounded-full font-medium ${
                    form.isActive
                      ? "bg-emerald-100 text-emerald-700"
                      : "bg-slate-100 text-slate-500"
                  }`}
                >
                  {form.isActive
                    ? isAr
                      ? "نشط"
                      : "Active"
                    : isAr
                      ? "غير نشط"
                      : "Inactive"}
                </span>
              </div>

              <div className="flex items-center gap-3 text-xs text-slate-500 mb-3">
                <span>
                  {form.fields?.length || 0} {isAr ? "حقول" : "fields"}
                </span>
                <span>
                  {isAr ? "عمليات الإرسال:" : "Submissions:"}{" "}
                  {form.submissions || 0}
                </span>
              </div>

              <div className="flex gap-1.5">
                <button
                  onClick={() => handleCopyEmbed(form.id)}
                  className="flex items-center gap-1 px-2.5 py-1.5 text-xs text-indigo-600 bg-indigo-50 rounded-lg hover:bg-indigo-100 transition-colors"
                >
                  <Copy className="h-3 w-3" />
                  {isAr ? "نسخ الكود" : "Copy Embed"}
                </button>
                <button
                  onClick={() => handleDelete(form.id)}
                  className="flex items-center gap-1 px-2.5 py-1.5 text-xs text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
                >
                  <Trash2 className="h-3 w-3" />
                  {isAr ? "حذف" : "Delete"}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
