"use client";

import { useState, useCallback } from "react";
import {
  Plus,
  Loader2,
  Trash2,
  ToggleLeft,
  ToggleRight,
  Settings,
} from "lucide-react";
import type { ScoringRuleOutput } from "@/lib/types/lead-crm.types";

interface ScoringRulesConfigProps {
  isAr: boolean;
  rules: ScoringRuleOutput[];
  onRefresh: () => void;
}

export default function ScoringRulesConfig({
  isAr,
  rules,
  onRefresh,
}: ScoringRulesConfigProps) {
  const [showCreate, setShowCreate] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newRule, setNewRule] = useState({
    name: "",
    category: "ENGAGEMENT" as string,
    condition: { type: "event", event: "" },
    points: 5,
  });

  const categoryLabels: Record<string, { en: string; ar: string }> = {
    ENGAGEMENT: { en: "Engagement", ar: "التفاعل" },
    DEMOGRAPHIC: { en: "Demographic", ar: "الديموغرافيا" },
    BEHAVIORAL: { en: "Behavioral", ar: "السلوك" },
    FIRMOGRAPHIC: { en: "Firmographic", ar: "بيانات الشركة" },
    DECAY: { en: "Decay", ar: "الاضمحلال" },
  };

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

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

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

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "قواعد التسجيل" : "Scoring Rules"}
          </h3>
          <p className="text-sm text-slate-500">
            {isAr
              ? "حدد كيف يتم تسجيل نقاط العملاء المحتملين"
              : "Configure how lead scores are calculated"}
          </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 Rule"}
        </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 Scoring Rule"}
          </h4>
          <div className="space-y-3">
            <div>
              <label className="text-xs font-medium text-slate-600 mb-1 block">
                {isAr ? "اسم القاعدة" : "Rule Name"}
              </label>
              <input
                value={newRule.name}
                onChange={(e) =>
                  setNewRule((prev) => ({ ...prev, name: e.target.value }))
                }
                placeholder={
                  isAr
                    ? "مثال: إرسال نموذج اتصال"
                    : "e.g. Contact Form Submission"
                }
                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 className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs font-medium text-slate-600 mb-1 block">
                  {isAr ? "الفئة" : "Category"}
                </label>
                <select
                  value={newRule.category}
                  onChange={(e) =>
                    setNewRule((prev) => ({
                      ...prev,
                      category: 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(categoryLabels).map(([key, label]) => (
                    <option key={key} value={key}>
                      {isAr ? label.ar : label.en}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="text-xs font-medium text-slate-600 mb-1 block">
                  {isAr ? "النقاط" : "Points"}
                </label>
                <input
                  type="number"
                  value={newRule.points}
                  onChange={(e) =>
                    setNewRule((prev) => ({
                      ...prev,
                      points: parseInt(e.target.value) || 0,
                    }))
                  }
                  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"
                />
              </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={!newRule.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>
      )}

      {/* Rules list */}
      {rules.length === 0 ? (
        <div className="text-center py-16 text-slate-400">
          <Settings className="h-10 w-10 mx-auto mb-3 opacity-50" />
          <p className="text-sm">
            {isAr
              ? "لا توجد قواعد تسجيل. أنشئ قواعد لحساب نقاط العملاء."
              : "No scoring rules yet. Create rules to calculate lead scores."}
          </p>
        </div>
      ) : (
        <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 bg-slate-50/50">
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                  {isAr ? "القاعدة" : "Rule"}
                </th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                  {isAr ? "الفئة" : "Category"}
                </th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                  {isAr ? "النقاط" : "Points"}
                </th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                  {isAr ? "الحالة" : "Status"}
                </th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {rules.map((rule) => (
                <tr
                  key={rule.id}
                  className="border-b border-slate-50 hover:bg-slate-50/50 transition-colors"
                >
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-slate-900">
                      {rule.name}
                    </p>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-xs px-2 py-1 bg-slate-100 text-slate-700 rounded-full">
                      {isAr
                        ? categoryLabels[rule.category]?.ar || rule.category
                        : categoryLabels[rule.category]?.en || rule.category}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`text-sm font-semibold ${
                        rule.points >= 0 ? "text-emerald-600" : "text-red-600"
                      }`}
                    >
                      {rule.points > 0 ? `+${rule.points}` : rule.points}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() => handleToggle(rule.id, rule.isActive)}
                      className="text-slate-500 hover:text-slate-700 transition-colors"
                    >
                      {rule.isActive ? (
                        <ToggleRight className="h-6 w-6 text-emerald-500" />
                      ) : (
                        <ToggleLeft className="h-6 w-6 text-slate-400" />
                      )}
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() => handleDelete(rule.id)}
                      className="p-1 rounded hover:bg-red-50 text-red-500 transition-colors"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
