"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import {
  RotateCcw, BarChart3, Check, Plus, Minus,
  Circle, ChevronRight, Loader2,
} from "lucide-react";

// ── Types ──
interface DhikrPreset {
  id: string;
  label: string;
  arabic: string;
  transliteration: string;
  translation: string;
  target: number;
}

interface DayStats {
  subhanallah: number;
  alhamdulillah: number;
  allahuakbar: number;
  custom: number;
  totalCount: number;
  sessionCount: number;
}

interface RecentSession {
  id: string;
  type: string;
  count: number;
  createdAt: string;
}

interface StatsResponse {
  dayStats: { subhanallah: number; alhamdulillah: number; allahuakbar: number; custom: number; totalCount: number; sessionCount: number };
  recentSessions: RecentSession[];
}

// ── Constants ──
const PRESETS: DhikrPreset[] = [
  { id: "subhanallah", label: "SubhanAllah", arabic: "سُبْحَانَ ٱللَّٰهِ", transliteration: "SubhanAllah", translation: "Glory be to Allah", target: 33 },
  { id: "alhamdulillah", label: "Alhamdulillah", arabic: "ٱلْحَمْدُ لِلَّٰهِ", transliteration: "Alhamdulillah", translation: "Praise be to Allah", target: 33 },
  { id: "allahuakbar", label: "Allahu Akbar", arabic: "ٱللَّٰهُ أَكْبَرُ", transliteration: "Allahu Akbar", translation: "Allah is the Greatest", target: 34 },
];

const COLORS: Record<string, { from: string; to: string; accent: string; ring: string }> = {
  subhanallah: { from: "from-emerald-900/30", to: "to-emerald-800/10", accent: "emerald", ring: "#10b981" },
  alhamdulillah: { from: "from-amber-900/30", to: "to-amber-800/10", accent: "amber", ring: "#f59e0b" },
  allahuakbar: { from: "from-sky-900/30", to: "to-sky-800/10", accent: "sky", ring: "#0ea5e9" },
  custom: { from: "from-purple-900/30", to: "to-purple-800/10", accent: "purple", ring: "#a855f7" },
};

const ALL_TARGETS = [
  { label: "33", value: 33 },
  { label: "99", value: 99 },
  { label: "100", value: 100 },
  { label: "500", value: 500 },
  { label: "1K", value: 1000 },
];

// ── Circular Progress ──
function CircularRing({ percent, size = 64, strokeWidth = 4, color = "#10b981" }: { percent: number; size?: number; strokeWidth?: number; color?: string }) {
  const r = (size - strokeWidth) / 2;
  const circ = 2 * Math.PI * r;
  const offset = circ * (1 - Math.min(percent, 1));
  return (
    <svg width={size} height={size} className="transform -rotate-90 shrink-0">
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth={strokeWidth} />
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round"
        strokeDasharray={circ} strokeDashoffset={offset} className="transition-all duration-300 ease-out" />
    </svg>
  );
}

// ── Main Component ──
export default function DhikrPage() {
  const { user, token, loading: authLoading } = useAuth();
  const router = useRouter();

  // State
  const [selectedPreset, setSelectedPreset] = useState<string>("subhanallah");
  const [count, setCount] = useState(0);
  const [customTarget, setCustomTarget] = useState(33);
  const [mode, setMode] = useState<"preset" | "custom">("preset");
  const [showTargetPicker, setShowTargetPicker] = useState(false);
  const [dayStats, setDayStats] = useState<DayStats | null>(null);
  const [recentSessions, setRecentSessions] = useState<RecentSession[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [showRecent, setShowRecent] = useState(false);
  const [showReset, setShowReset] = useState(false);

  const buttonRef = useRef<HTMLButtonElement>(null);
  const [ripples, setRipples] = useState<{ id: number; x: number; y: number }[]>([]);
  const nextRippleId = useRef(0);

  const lastTapRef = useRef(0);
  const countRef = useRef(count);
  countRef.current = count;

  // ── Auth redirect ──
  useEffect(() => {
    if (!authLoading && !token) router.push("/auth");
  }, [authLoading, token, router]);

  // ── Fetch stats ──
  const fetchStats = useCallback(async () => {
    if (!token) return;
    try {
      const res = await fetch("/mobile/api/dhikr/stats", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data: StatsResponse = await res.json();
        setDayStats(data.dayStats);
        setRecentSessions(data.recentSessions);
      }
    } catch {} finally {
      setLoading(false);
    }
  }, [token]);

  useEffect(() => { if (token) fetchStats(); }, [token, fetchStats]);

  // ── Log session to API ──
  const logSession = useCallback(async (type: string, cnt: number, tgt: number) => {
    if (!token || cnt === 0) return;
    setSaving(true);
    try {
      await fetch("/mobile/api/dhikr/stats", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
        body: JSON.stringify({ type, count: cnt, target: tgt, completed: true }),
      });
      await fetchStats();
    } catch {} finally {
      setSaving(false);
    }
  }, [token, fetchStats]);

  // ── Tap counter ──
  const handleTap = (e: React.MouseEvent | React.TouchEvent) => {
    // Haptic feedback
    if (navigator.vibrate) navigator.vibrate(10);

    // Ripple effect
    const rect = buttonRef.current?.getBoundingClientRect();
    if (rect) {
      let x: number, y: number;
      if ("touches" in e) {
        x = e.touches[0].clientX - rect.left;
        y = e.touches[0].clientY - rect.top;
      } else {
        x = e.clientX - rect.left;
        y = e.clientY - rect.top;
      }
      const id = nextRippleId.current++;
      setRipples((prev) => [...prev.slice(-4), { id, x, y }]);
      setTimeout(() => setRipples((prev) => prev.filter((r) => r.id !== id)), 600);
    }

    setCount((c) => c + 1);
    lastTapRef.current = Date.now();
  };

  // ── Long-press -> reset ──
  const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const handlePointerDown = () => {
    longPressTimer.current = setTimeout(() => setShowReset(true), 500);
  };
  const handlePointerUp = () => {
    if (longPressTimer.current) clearTimeout(longPressTimer.current);
  };

  // ── Reset ──
  const resetCount = () => {
    setCount(0);
    setShowReset(false);
  };

  // ── Switch preset ──
  const switchPreset = (id: string) => {
    if (count > 0) {
      // Auto-save current session
      const preset = PRESETS.find((p) => p.id === selectedPreset);
      const type = preset ? preset.id : "custom";
      const tgt = preset ? preset.target : customTarget;
      logSession(type, count, tgt);
    }
    setSelectedPreset(id);
    setCount(0);
    setMode("preset");
  };

  // ── Start custom mode ──
  const startCustom = () => {
    if (count > 0) {
      const preset = PRESETS.find((p) => p.id === selectedPreset);
      logSession(preset ? preset.id : "custom", count, preset ? preset.target : customTarget);
    }
    setMode("custom");
    setCount(0);
  };

  const target = mode === "custom" ? customTarget : (PRESETS.find((p) => p.id === selectedPreset)?.target ?? 33);
  const percent = target > 0 ? count / target : 0;
  const isComplete = count > 0 && count >= target;
  const currentPreset = PRESETS.find((p) => p.id === selectedPreset);
  const colors = COLORS[mode === "custom" ? "custom" : selectedPreset] || COLORS.custom;

  // ── Render ──
  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      {/* ── Header ── */}
      <div className="px-4 pt-6 pb-3 flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold text-white flex items-center gap-2">
            📿 Dhikr
          </h1>
          <p className="text-xs text-gray-500 mt-0.5">Digital Tasbih Counter</p>
        </div>
        <div className="flex gap-2">
          <button onClick={() => setShowRecent((s) => !s)}
            className="w-10 h-10 rounded-xl bg-[#111118] border border-gray-800/60 flex items-center justify-center active:scale-95 transition"
            title="Today's stats">
            <BarChart3 size={16} className="text-gray-400" />
          </button>
          <button onClick={() => { setCount(0); setMode("preset"); setSelectedPreset("subhanallah"); }}
            className="w-10 h-10 rounded-xl bg-[#111118] border border-gray-800/60 flex items-center justify-center active:scale-95 transition"
            title="Reset">
            <RotateCcw size={16} className="text-gray-400" />
          </button>
        </div>
      </div>

      {/* ── Preset Selector ── */}
      <div className="mx-4 mb-5">
        <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-none">
          {PRESETS.map((p) => {
            const active = selectedPreset === p.id && mode === "preset";
            const c = COLORS[p.id];
            return (
              <button key={p.id} onClick={() => switchPreset(p.id)}
                className={`flex-1 min-w-[100px] rounded-2xl px-3 py-3 border text-center transition-all active:scale-95
                  ${active ? `bg-gradient-to-br ${c.from} ${c.to} border-${c.accent}-500/50` : "bg-[#111118] border-gray-800/60"}`}>
                <p className={`text-sm font-semibold ${active ? "text-white" : "text-gray-400"}`}>{p.label}</p>
                <p className={`text-xs mt-0.5 ${active ? "text-gray-300" : "text-gray-600"}`}>
                  {active ? `${count}/${p.target}` : `/${p.target}`}
                </p>
              </button>
            );
          })}
          <button onClick={startCustom}
            className={`flex-1 min-w-[80px] rounded-2xl px-3 py-3 border text-center transition-all active:scale-95
              ${mode === "custom" ? "bg-gradient-to-br from-purple-900/30 to-purple-800/10 border-purple-500/50" : "bg-[#111118] border-gray-800/60"}`}>
            <p className={`text-sm font-semibold ${mode === "custom" ? "text-white" : "text-gray-400"}`}>Custom</p>
            <p className={`text-xs mt-0.5 ${mode === "custom" ? "text-gray-300" : "text-gray-600"}`}>
              {mode === "custom" ? `${count}/${customTarget}` : "🎯"}
            </p>
          </button>
        </div>
      </div>

      {/* ── Count Display & Counter ── */}
      <div className="mx-4 mb-5">
        <div className="relative bg-gradient-to-br from-[#111118] to-gray-900/80 border border-gray-800/60 rounded-3xl p-6 overflow-hidden">
          {/* Decorative glow */}
          <div className={`absolute -top-16 -right-16 w-40 h-40 bg-${colors.accent}-500/5 rounded-full blur-3xl`} />

          {/* Arabic text + progress */}
          <div className="relative flex flex-col items-center">
            {/* Circular progress + count */}
            <div className="relative mb-4">
              <CircularRing percent={percent} size={140} strokeWidth={6} color={colors.ring} />
              <div className="absolute inset-0 flex flex-col items-center justify-center">
                {isComplete ? (
                  <div className="text-center">
                    <Check size={32} className="text-green-400 mx-auto mb-1" />
                    <p className="text-lg font-bold text-green-400">Complete!</p>
                  </div>
                ) : (
                  <>
                    <p className="text-5xl font-bold text-white tabular-nums">{count}</p>
                    <p className="text-xs text-gray-500 mt-0.5">/ {target}</p>
                  </>
                )}
              </div>
            </div>

            {/* Arabic dhikr */}
            {mode === "preset" && currentPreset && (
              <p className="text-2xl font-arabic text-white mb-1 text-center" dir="rtl">{currentPreset.arabic}</p>
            )}
            {mode === "custom" && (
              <p className="text-lg text-gray-300 mb-1 text-center">Custom Dhikr</p>
            )}
            {mode === "preset" && currentPreset && (
              <p className="text-xs text-gray-500 italic mb-4">{currentPreset.translation}</p>
            )}
            {mode === "custom" && (
              <p className="text-xs text-gray-500 italic mb-4">Set your own count target</p>
            )}

            {/* Tap Button */}
            <button
              ref={buttonRef}
              onMouseDown={handlePointerDown}
              onMouseUp={handlePointerUp}
              onMouseLeave={handlePointerUp}
              onTouchStart={(e) => { handlePointerDown(); handleTap(e); }}
              onTouchEnd={handlePointerUp}
              onClick={(e) => { if (e.type === "click") handleTap(e); }}
              className="relative w-48 h-48 rounded-full bg-gradient-to-br from-gray-800 to-gray-900 border-2 border-gray-700/50
                active:scale-95 active:from-gray-700 active:to-gray-800 transition-all duration-100
                shadow-lg overflow-hidden select-none touch-none"
              style={{ WebkitTapHighlightColor: "transparent" }}
            >
              {/* Ripple effects */}
              {ripples.map((r) => (
                <span key={r.id} className="absolute w-4 h-4 rounded-full bg-white/20 animate-ping pointer-events-none"
                  style={{ left: r.x - 8, top: r.y - 8 }} />
              ))}
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="text-center">
                  <p className="text-xs text-gray-500 mb-1">Tap to count</p>
                  {count === 0 && (
                    <p className="text-[10px] text-gray-600">Long-press to reset</p>
                  )}
                </div>
              </div>
            </button>

            {/* +/- Buttons */}
            <div className="flex items-center gap-6 mt-4">
              <button onClick={() => setCount((c) => Math.max(0, c - 1))}
                className="w-12 h-12 rounded-xl bg-gray-800/60 border border-gray-700/40 flex items-center justify-center active:scale-90 transition">
                <Minus size={18} className="text-gray-400" />
              </button>

              {mode === "custom" && (
                <button onClick={() => setShowTargetPicker(true)}
                  className="px-4 h-12 rounded-xl bg-purple-900/20 border border-purple-700/30 text-purple-300 text-sm font-medium active:scale-95 transition">
                  Target: {customTarget}
                </button>
              )}

              <button onClick={() => setCount((c) => c + 10)}
                className="w-12 h-12 rounded-xl bg-gray-800/60 border border-gray-700/40 flex items-center justify-center active:scale-90 transition">
                <Plus size={18} className="text-gray-400" />
              </button>
            </div>

            {/* Complete button */}
            {count > 0 && (
              <button onClick={() => {
                const type = mode === "preset" && currentPreset ? currentPreset.id : "custom";
                logSession(type, count, target);
                setCount(0);
              }} disabled={saving}
                className="mt-4 w-full py-3.5 bg-gradient-to-r from-emerald-600 to-green-600 hover:from-emerald-500 hover:to-green-500
                  disabled:opacity-50 text-white text-sm font-semibold rounded-xl active:scale-[0.98] transition-all min-h-[44px] flex items-center justify-center gap-2">
                {saving ? <Loader2 size={16} className="animate-spin" /> : <Check size={16} />}
                {saving ? "Saving..." : "Save & Complete Session"}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* ── Stats / Recent Sessions Panel ── */}
      {showRecent && dayStats && (
        <div className="mx-4 mb-5">
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
            <h3 className="text-sm font-semibold text-white mb-3">Today's Dhikr</h3>
            <div className="space-y-2">
              <StatRow label="SubhanAllah" value={dayStats.subhanallah} icon="🕌" />
              <StatRow label="Alhamdulillah" value={dayStats.alhamdulillah} icon="🍃" />
              <StatRow label="Allahu Akbar" value={dayStats.allahuakbar} icon="⭐" />
              <StatRow label="Custom" value={dayStats.custom} icon="📿" />
              <div className="border-t border-gray-800/60 pt-2 mt-2">
                <StatRow label="Total Count" value={dayStats.totalCount} icon="📊" highlight />
                <StatRow label="Sessions" value={dayStats.sessionCount} icon="🔄" />
              </div>
            </div>

            {recentSessions.length > 0 && (
              <>
                <h3 className="text-sm font-semibold text-white mt-4 mb-2">Recent Sessions</h3>
                <div className="space-y-1.5 max-h-40 overflow-y-auto">
                  {recentSessions.slice(0, 10).map((s) => (
                    <div key={s.id} className="flex items-center justify-between text-xs text-gray-500 bg-gray-900/40 rounded-lg px-3 py-2">
                      <span className="font-medium text-gray-400 capitalize">{s.type}</span>
                      <span>+{s.count}</span>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
      )}

      {/* ── Target Picker Modal (custom mode) ── */}
      {showTargetPicker && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
          onClick={() => setShowTargetPicker(false)}>
          <div className="bg-[#1a1a25] border border-gray-800 rounded-2xl p-6 w-full max-w-xs"
            onClick={(e) => e.stopPropagation()}>
            <h3 className="text-sm font-semibold text-white mb-4">Set Target</h3>
            <div className="grid grid-cols-3 gap-3 mb-4">
              {ALL_TARGETS.map((t) => (
                <button key={t.value} onClick={() => { setCustomTarget(t.value); setShowTargetPicker(false); }}
                  className={`py-3 rounded-xl border text-sm font-medium transition-all active:scale-95
                    ${customTarget === t.value ? "bg-purple-900/30 border-purple-500/50 text-purple-300" : "bg-gray-800/40 border-gray-700/40 text-gray-400"}`}>
                  {t.label}
                </button>
              ))}
            </div>
            <p className="text-xs text-gray-600 text-center">Or close to keep current ({customTarget})</p>
          </div>
        </div>
      )}

      {/* ── Reset confirmation ── */}
      {showReset && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
          onClick={() => setShowReset(false)}>
          <div className="bg-[#1a1a25] border border-gray-800 rounded-2xl p-6 w-full max-w-xs text-center"
            onClick={(e) => e.stopPropagation()}>
            <p className="text-sm text-gray-300 mb-4">Reset counter? Current count: {count}</p>
            <div className="flex gap-3">
              <button onClick={() => setShowReset(false)}
                className="flex-1 py-3 bg-gray-800/60 border border-gray-700/40 text-gray-400 text-sm rounded-xl active:scale-95 transition">Cancel</button>
              <button onClick={resetCount}
                className="flex-1 py-3 bg-red-900/30 border border-red-700/40 text-red-300 text-sm rounded-xl active:scale-95 transition">Reset</button>
            </div>
          </div>
        </div>
      )}

      {/* ── Loader ── */}
      {(authLoading || loading) && (
        <div className="flex items-center justify-center py-10">
          <Loader2 size={20} className="text-[#D4AF37] animate-spin" />
        </div>
      )}
    </div>
  );
}

function StatRow({ label, value, icon, highlight }: { label: string; value: number; icon: string; highlight?: boolean }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-xs text-gray-500 flex items-center gap-1.5">
        <span>{icon}</span> {label}
      </span>
      <span className={`text-xs font-bold ${highlight ? "text-[#D4AF37]" : "text-gray-300"}`}>
        {value.toLocaleString()}
      </span>
    </div>
  );
}
