"use client";

import { useState, useEffect } from "react";
import { Check, Loader2, RotateCcw } from "lucide-react";
import { Modal, ModalBody, ModalFooter } from "@/components/ui/modal";
import type { ConversionTier } from "@/lib/conversions/tiers";

// ─── Types ──────────────────────────────────────────────────────────────────

export interface ConversionTypeRow {
  conversionType: string;
  tier: ConversionTier | "unknown";
  isCounted: boolean;
  displayLabel: string;
  isCustom: boolean;
  defaultTier: ConversionTier | "unknown";
  defaultLabel: string;
  count?: number;
}

interface Props {
  open: boolean;
  onClose: () => void;
  brandId: string;
  rows: ConversionTypeRow[];
  sessions: number;
  onSaved: () => void;
}

// Tier display labels shown in the Tier dropdown.
// "completed" -> "Action": user completed a final conversion action.
// "intent" -> "Signal": user signaled intent (phone click, form start, etc.).
// "signal" -> "Engagement": broader engagement signals that are not yet intent.
// Both Action and Signal events count toward the total when "Counts?" is checked.
const TIER_OPTIONS: Array<{ value: ConversionTier | "unknown"; label: string }> = [
  { value: "completed", label: "Action" },
  { value: "intent", label: "Signal" },
  { value: "signal", label: "Engagement" },
  { value: "unknown", label: "Unknown" },
];

// ─── ConversionSettingsModal ─────────────────────────────────────────────────

export function ConversionSettingsModal({ open, onClose, brandId, rows, sessions, onSaved }: Props) {
  const [localRows, setLocalRows] = useState<ConversionTypeRow[]>([]);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [resetting, setResetting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) { setLocalRows(rows.map((r) => ({ ...r }))); setSaved(false); setError(null); }
    // rows is intentionally excluded: snapshot on open only, never reset mid-session
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  function toggleCounted(type: string) {
    setLocalRows((prev) =>
      prev.map((r) => r.conversionType === type ? { ...r, isCounted: !r.isCounted } : r),
    );
  }

  function setTier(type: string, tier: ConversionTier | "unknown") {
    setLocalRows((prev) =>
      prev.map((r) => {
        if (r.conversionType !== type) return r;
        return { ...r, tier };
      }),
    );
  }

  const previewCounted = localRows.reduce((s, r) => s + (r.isCounted ? (r.count ?? 0) : 0), 0);
  const originalCounted = rows.reduce((s, r) => s + (r.isCounted ? (r.count ?? 0) : 0), 0);
  const previewRate = sessions > 0 ? ((previewCounted / sessions) * 100).toFixed(2) : "0.00";
  const originalRate = sessions > 0 ? ((originalCounted / sessions) * 100).toFixed(2) : "0.00";
  const changed = previewCounted !== originalCounted || localRows.some((r, i) => r.tier !== rows[i]?.tier);

  async function handleSave() {
    setSaving(true);
    setError(null);
    try {
      const updates = localRows.map((r) => ({
        conversionType: r.conversionType,
        isCounted: r.isCounted,
        tierOverride: r.tier !== r.defaultTier ? r.tier : null,
        displayLabel: null,
      }));
      const res = await fetch(`/api/brands/${brandId}/conversion-config`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ updates }),
      });
      if (!res.ok) throw new Error("Save failed");
      setSaved(true);
      // Brief confirmation flash before closing so the user sees feedback.
      setTimeout(() => {
        onSaved();
        onClose();
      }, 500);
    } catch {
      setError("Failed to save. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  async function handleReset() {
    setResetting(true);
    setError(null);
    try {
      const res = await fetch(`/api/brands/${brandId}/conversion-config`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reset: true }),
      });
      if (!res.ok) throw new Error("Reset failed");
      setSaved(true);
      setTimeout(() => {
        onSaved();
        onClose();
      }, 500);
    } catch {
      setError("Failed to reset. Please try again.");
    } finally {
      setResetting(false);
    }
  }

  const busy = saving || resetting || saved;

  return (
    <Modal open={open} onClose={onClose} title="Configure Conversions" maxWidth="max-w-2xl">
      <ModalBody className="px-0 py-0">
        <div className="px-5 py-3 border-b border-slate-100 bg-slate-50/60">
          <p className="text-xs text-slate-600 leading-relaxed">
            Choose which event types count toward your total conversions. Action events are final conversions; Signal events show intent. Both can count if you check the box. Unchecked events still appear in the dashboard but are not included in your conversion total.
          </p>
        </div>

        {/* Table */}
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[10px] font-semibold uppercase tracking-wider text-slate-400 bg-slate-50/40 border-b border-slate-100">
                <th className="px-5 py-2.5">Event Type</th>
                <th className="px-3 py-2.5 text-right tabular-nums">Last 28d</th>
                <th className="px-3 py-2.5">Tier</th>
                <th className="px-3 py-2.5 text-center">Counts?</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {localRows.map((r) => (
                <tr key={r.conversionType} className="hover:bg-slate-50/60 transition-colors">
                  <td className="px-5 py-2.5 font-medium text-slate-800">
                    {r.displayLabel}
                    <span className="ml-1.5 text-[10px] font-mono text-slate-400">{r.conversionType}</span>
                  </td>
                  <td className="px-3 py-2.5 text-right tabular-nums text-slate-600 font-semibold">
                    {(r.count ?? 0).toLocaleString()}
                  </td>
                  <td className="px-3 py-2.5">
                    <select
                      value={r.tier}
                      onChange={(e) => setTier(r.conversionType, e.target.value as ConversionTier | "unknown")}
                      className="text-xs border border-slate-200 rounded-md px-2 py-1 bg-white text-slate-700 focus:outline-none focus:ring-1 focus:ring-brand-500"
                    >
                      {TIER_OPTIONS.map((opt) => (
                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                      ))}
                    </select>
                  </td>
                  <td className="px-3 py-2.5 text-center">
                    <input
                      type="checkbox"
                      checked={r.isCounted}
                      onChange={() => toggleCounted(r.conversionType)}
                      className="w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer"
                    />
                  </td>
                </tr>
              ))}
              {localRows.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-5 py-6 text-center text-xs text-slate-400">
                    No conversion types captured yet.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Preview */}
        <div className="px-5 py-3 border-t border-slate-100 bg-slate-50/60">
          <p className="text-[10px] font-semibold uppercase tracking-wider text-slate-400 mb-1.5">Preview</p>
          <div className="flex items-center gap-6 text-sm">
            <div>
              <span className="font-bold text-slate-900 tabular-nums">{previewCounted.toLocaleString()}</span>
              <span className="text-slate-500 ml-1">counted conversions</span>
              {changed && originalCounted !== previewCounted && (
                <span className="text-slate-400 ml-1.5 text-xs">(was {originalCounted.toLocaleString()})</span>
              )}
            </div>
            <div>
              <span className="font-bold text-emerald-600 tabular-nums">{previewRate}%</span>
              <span className="text-slate-500 ml-1">conv. rate</span>
              {changed && previewRate !== originalRate && (
                <span className="text-slate-400 ml-1.5 text-xs">(was {originalRate}%)</span>
              )}
            </div>
          </div>
        </div>

        {error && (
          <div className="px-5 py-2.5 bg-red-50 border-t border-red-100 flex items-center justify-between gap-3">
            <p className="text-xs text-red-600">{error}</p>
            <button
              onClick={handleSave}
              className="text-xs font-semibold text-red-600 hover:text-red-700 underline shrink-0"
            >
              Retry
            </button>
          </div>
        )}
      </ModalBody>

      <ModalFooter>
        <button
          onClick={handleReset}
          disabled={busy}
          className="flex items-center gap-1.5 text-xs text-slate-500 hover:text-slate-700 px-3 py-1.5 rounded-lg hover:bg-slate-100 transition-colors mr-auto disabled:opacity-50"
        >
          <RotateCcw className="w-3 h-3" />
          Reset to Defaults
        </button>
        <button
          onClick={onClose}
          disabled={busy}
          className="text-xs text-slate-600 hover:text-slate-800 px-3 py-1.5 rounded-lg hover:bg-slate-100 transition-colors"
        >
          Cancel
        </button>
        <button
          onClick={handleSave}
          disabled={busy}
          className="inline-flex items-center gap-1.5 text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 px-4 py-1.5 rounded-lg transition-colors disabled:opacity-50 min-w-[64px] justify-center"
        >
          {saved ? (
            <><Check className="w-3.5 h-3.5" /> Saved</>
          ) : saving ? (
            <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Saving</>
          ) : (
            "Save"
          )}
        </button>
      </ModalFooter>
    </Modal>
  );
}
