"use client";

import { useState, useCallback } from "react";
import {
  Plus,
  Loader2,
  Play,
  Pause,
  Trash2,
  Mail,
  MessageSquare,
  Clock,
  Users,
  Zap,
} from "lucide-react";
import type { NurtureSequenceOutput } from "@/lib/types/lead-crm.types";

interface NurtureSequencesListProps {
  isAr: boolean;
  sequences: NurtureSequenceOutput[];
  onRefresh: () => void;
}

export default function NurtureSequencesList({
  isAr,
  sequences,
  onRefresh,
}: NurtureSequencesListProps) {
  const [showCreate, setShowCreate] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newSequence, setNewSequence] = useState({
    name: "",
    triggerType: "MANUAL" as string,
    steps: [
      {
        stepOrder: 1,
        channel: "EMAIL" as string,
        delayHours: 0,
        config: { subject: "", body: "" },
      },
    ],
  });

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

  const handleToggle = useCallback(
    async (seqId: string, active: boolean) => {
      try {
        await fetch(`/api/leads/nurture/${seqId}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ active: !active }),
        });
        onRefresh();
      } catch {
        // silent
      }
    },
    [onRefresh],
  );

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

  const channelIcons: Record<string, React.ReactNode> = {
    EMAIL: <Mail className="h-3 w-3" />,
    WHATSAPP: <MessageSquare className="h-3 w-3" />,
    SMS: <MessageSquare className="h-3 w-3" />,
    WAIT: <Clock className="h-3 w-3" />,
  };

  const triggerLabels: Record<string, { en: string; ar: string }> = {
    MANUAL: { en: "Manual", ar: "يدوي" },
    NEW_LEAD: { en: "New Lead", ar: "عميل جديد" },
    SCORE_CHANGE: { en: "Score Change", ar: "تغيير النقاط" },
    STATUS_CHANGE: { en: "Status Change", ar: "تغيير الحالة" },
    FORM_SUBMISSION: { en: "Form Submission", ar: "إرسال نموذج" },
    INACTIVITY: { en: "Inactivity", 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 ? "سلاسل الرعاية" : "Nurture Sequences"}
          </h3>
          <p className="text-sm text-slate-500">
            {isAr
              ? "أتمتة التواصل مع العملاء المحتملين"
              : "Automate lead nurturing with multi-channel sequences"}
          </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 Sequence"}
        </button>
      </div>

      {/* Create 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 Nurture Sequence"}
          </h4>
          <div className="space-y-3">
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "اسم السلسلة" : "Sequence Name"}
              </label>
              <input
                value={newSequence.name}
                onChange={(e) =>
                  setNewSequence((prev) => ({ ...prev, name: e.target.value }))
                }
                placeholder={
                  isAr ? "مثال: ترحيب عملاء جدد" : "e.g. New Lead Welcome"
                }
                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 ? "المحفّز" : "Trigger"}
              </label>
              <select
                value={newSequence.triggerType}
                onChange={(e) =>
                  setNewSequence((prev) => ({
                    ...prev,
                    triggerType: e.target.value,
                  }))
                }
                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"
              >
                {Object.entries(triggerLabels).map(([key, label]) => (
                  <option key={key} value={key}>
                    {isAr ? label.ar : label.en}
                  </option>
                ))}
              </select>
            </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={!newSequence.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>
      )}

      {/* Sequences list */}
      {sequences.length === 0 ? (
        <div className="text-center py-16 text-slate-400">
          <Zap className="h-10 w-10 mx-auto mb-3 opacity-50" />
          <p className="text-sm">
            {isAr
              ? "لا توجد سلاسل رعاية. أنشئ واحدة لأتمتة تواصلك."
              : "No nurture sequences yet. Create one to automate outreach."}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {sequences.map((seq) => (
            <div
              key={seq.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>
                  <div className="flex items-center gap-2">
                    <h4 className="text-sm font-semibold text-slate-900">
                      {seq.name}
                    </h4>
                    <span
                      className={`text-[10px] px-2 py-0.5 rounded-full font-medium ${
                        seq.isActive
                          ? "bg-emerald-100 text-emerald-700"
                          : "bg-slate-100 text-slate-500"
                      }`}
                    >
                      {seq.isActive
                        ? isAr
                          ? "نشط"
                          : "Active"
                        : isAr
                          ? "متوقف"
                          : "Paused"}
                    </span>
                  </div>
                  <p className="text-xs text-slate-500 mt-0.5">
                    {isAr ? "المحفّز:" : "Trigger:"}{" "}
                    {isAr
                      ? triggerLabels[seq.triggerType]?.ar || seq.triggerType
                      : triggerLabels[seq.triggerType]?.en || seq.triggerType}
                  </p>
                </div>
                <div className="flex gap-1.5">
                  <button
                    onClick={() => handleToggle(seq.id, seq.isActive)}
                    className={`p-1.5 rounded-lg transition-colors ${
                      seq.isActive
                        ? "text-amber-600 hover:bg-amber-50"
                        : "text-emerald-600 hover:bg-emerald-50"
                    }`}
                    title={seq.isActive ? "Pause" : "Activate"}
                  >
                    {seq.isActive ? (
                      <Pause className="h-4 w-4" />
                    ) : (
                      <Play className="h-4 w-4" />
                    )}
                  </button>
                  <button
                    onClick={() => handleDelete(seq.id)}
                    className="p-1.5 rounded-lg text-red-500 hover:bg-red-50 transition-colors"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>

              {/* Steps preview */}
              <div className="flex items-center gap-1.5 flex-wrap">
                {seq.steps?.map((step, idx) => (
                  <div key={idx} className="flex items-center gap-1">
                    <span className="flex items-center gap-1 px-2 py-1 bg-slate-50 rounded-lg text-xs text-slate-600">
                      {channelIcons[step.channel] || (
                        <Clock className="h-3 w-3" />
                      )}
                      {step.channel}
                    </span>
                    {idx < (seq.steps?.length || 0) - 1 && (
                      <span className="text-slate-300 text-xs">&rarr;</span>
                    )}
                  </div>
                ))}
              </div>

              {/* Stats */}
              <div className="flex items-center gap-4 mt-3 text-xs text-slate-500">
                <span className="flex items-center gap-1">
                  <Users className="h-3 w-3" />
                  {seq.enrolledCount || 0} {isAr ? "مسجّل" : "enrolled"}
                </span>
                <span>
                  {seq.steps?.length || 0} {isAr ? "خطوات" : "steps"}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
