"use client";
import { useState, useEffect } from "react";
import { Smartphone, CheckCircle, AlertCircle, RefreshCw, Zap, Shield, Send, MessageSquare, ChevronDown, ChevronUp, Trash2 } from "lucide-react";

const FAQ = [
  { q: "Will this affect my WhatsApp?", a: "No. It connects as a linked device — just like WhatsApp Web. Your phone works normally." },
  { q: "Can patients see it's automated?", a: "No. Messages come from your clinic's WhatsApp number. Looks like a personal message." },
  { q: "What if my phone goes offline?", a: "Messages queue and send once your phone reconnects to the internet." },
  { q: "Can I disconnect anytime?", a: "Yes. From this page or from WhatsApp → Linked Devices on your phone." },
  { q: "Is my data secure?", a: "We never store WhatsApp credentials. QR-only auth. End-to-end encrypted by WhatsApp." },
];

export default function ConnectPage() {
  const [status, setStatus] = useState<"disconnected" | "qr_pending" | "connected">("disconnected");
  const [qrCode, setQrCode] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [openFaq, setOpenFaq] = useState<number | null>(null);
  const [wahaReachable, setWahaReachable] = useState<boolean | null>(null);
  const [wahaError, setWahaError] = useState<string | null>(null);

  const checkStatus = async () => {
    try {
      const res = await fetch("/api/whatsapp/status");
      const data = await res.json();
      setStatus(data.status);
      if (data.qrCode) setQrCode(data.qrCode);
      setWahaReachable(data.wahaReachable ?? null);
      setWahaError(data.wahaError ?? null);
    } catch { /* silent */ }
  };

  useEffect(() => { checkStatus(); const i = setInterval(checkStatus, 5000); return () => clearInterval(i); }, []);

  const handleConnect = async () => {
    setLoading(true); setError(null);
    try {
      const res = await fetch("/api/whatsapp/connect", { method: "POST" });
      const data = await res.json();
      if (data.error) setError(data.error);
      else { setStatus("qr_pending"); if (data.qrCode) setQrCode(data.qrCode); }
    } catch { setError("Connection failed. Is Waha running on port 3001?"); }
    finally { setLoading(false); }
  };

  const handleDisconnect = async () => {
    if (!confirm("Disconnect WhatsApp? Pending reminders won't be sent until you reconnect.")) return;
    setLoading(true);
    try { await fetch("/api/whatsapp/disconnect", { method: "POST" }); setStatus("disconnected"); setQrCode(null); }
    catch { setError("Failed to disconnect"); }
    finally { setLoading(false); }
  };

  const handleDelete = async () => {
    if (!confirm("⚠️ Delete WhatsApp connection completely?\n\nThis will remove all session data. You'll need to scan the QR code again to reconnect.")) return;
    setLoading(true);
    try { await fetch("/api/whatsapp/delete", { method: "POST" }); setStatus("disconnected"); setQrCode(null); }
    catch { setError("Failed to delete connection"); }
    finally { setLoading(false); }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-5">
      <div className="flex items-center gap-3 animate-fade-in">
        <div className="w-10 h-10 rounded-xl bg-green-500/10 flex items-center justify-center"><Smartphone size={18} className="text-green-500" /></div>
        <div><h1 className="text-xl font-bold text-dark">Connect WhatsApp</h1><p className="text-xs text-muted">Link your clinic&apos;s WhatsApp for automatic reminders</p></div>
      </div>

      {/* Docker / WAHA server warning */}
      {wahaReachable === false && (
        <div className="flex items-start gap-3 bg-red-50 border border-red-200 rounded-xl px-4 py-3 animate-fade-in">
          <AlertCircle size={18} className="text-red-500 mt-0.5 shrink-0" />
          <div>
            <p className="text-sm font-semibold text-red-700">WhatsApp server is unreachable</p>
            <p className="text-xs text-red-600 mt-0.5">
              {wahaError?.includes("Docker") || wahaError?.includes("timeout")
                ? "Docker Desktop is not running. Start Docker Desktop to resume WhatsApp reminders."
                : `Error: ${wahaError}`}
            </p>
          </div>
        </div>
      )}

      {/* Main card */}
      <div className="card overflow-hidden">
        {/* Status banner */}
        <div className={`px-5 py-3.5 flex items-center gap-3 ${
          status === "connected" ? "bg-emerald-500" : status === "qr_pending" ? "bg-amber-500" : "bg-gray-700"
        }`}>
          <div className="w-8 h-8 bg-white/15 rounded-lg flex items-center justify-center backdrop-blur-sm">
            {status === "connected" ? <Zap size={16} className="text-white" /> : <Smartphone size={16} className="text-white" />}
          </div>
          <div className="flex-1">
            <p className="text-white text-sm font-semibold">
              {status === "connected" ? "Connected" : status === "qr_pending" ? "Waiting for scan..." : "Disconnected"}
            </p>
            <p className="text-white/70 text-[11px]">
              {status === "connected" ? "Reminders are sending automatically" : status === "qr_pending" ? "Scan the QR code below" : "Connect to start sending"}
            </p>
          </div>
          <span className={`w-2.5 h-2.5 rounded-full ${status === "connected" ? "bg-white animate-pulse-soft" : "bg-white/30"}`} />
        </div>

        <div className="p-8">
          {/* Connected */}
          {status === "connected" && (
            <div className="text-center space-y-5">
              <div className="w-16 h-16 bg-emerald-50 rounded-full flex items-center justify-center mx-auto">
                <CheckCircle size={32} className="text-emerald-500" />
              </div>
              <div>
                <h2 className="text-lg font-bold mb-1">All Systems Go ✅</h2>
                <p className="text-sm text-gray-500 max-w-sm mx-auto">Your WhatsApp is linked. Every booked appointment triggers the full reminder sequence automatically.</p>
              </div>
              <div className="grid grid-cols-3 gap-3 max-w-xs mx-auto">
                {[
                  { icon: Send, label: "Auto-Send", sub: "Active" },
                  { icon: MessageSquare, label: "Replies", sub: "Detected" },
                  { icon: Shield, label: "Encrypted", sub: "E2E" },
                ].map((f, i) => (
                  <div key={i} className="bg-gray-50 rounded-lg p-2.5 text-center">
                    <f.icon size={14} className="text-gray-400 mx-auto mb-1" />
                    <p className="text-[10px] font-semibold text-dark">{f.label}</p>
                    <p className="text-[9px] text-emerald-500">{f.sub}</p>
                  </div>
                ))}
              </div>
              <div className="flex items-center justify-center gap-3">
                <button onClick={handleDisconnect} disabled={loading} className="btn-danger btn-sm">
                  {loading ? "..." : <><Smartphone size={14} /> Disconnect</>}
                </button>
                <button onClick={handleDelete} disabled={loading} className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold rounded-lg border-2 border-red-200 text-red-500 hover:bg-red-50 hover:border-red-300 transition-all">
                  {loading ? "..." : <><Trash2 size={14} /> Delete Connection</>}
                </button>
              </div>
            </div>
          )}

          {/* QR Scan */}
          {status === "qr_pending" && (
            <div className="text-center space-y-5">
              <div>
                <h2 className="text-lg font-bold mb-1">Scan with your phone</h2>
                <p className="text-sm text-gray-500">WhatsApp → ⋮ → Linked Devices → Link a Device</p>
              </div>
              {qrCode ? (
                <div className="inline-block bg-white border border-gray-200 rounded-xl p-5 shadow-md">
                  <img src={qrCode} alt="QR Code" className="w-48 h-48" />
                </div>
              ) : (
                <div className="inline-block bg-gray-50 rounded-xl p-10">
                  <RefreshCw size={28} className="text-gray-300 animate-spin mx-auto" />
                  <p className="text-xs text-gray-400 mt-2">Loading QR...</p>
                </div>
              )}
              <div className="flex items-center justify-center gap-2 text-amber-600 bg-amber-50 rounded-lg p-2.5 max-w-xs mx-auto">
                <AlertCircle size={14} className="shrink-0" />
                <span className="text-[11px] font-medium">QR refreshes automatically. Keep this page open.</span>
              </div>
              <div className="flex items-center justify-center gap-3">
                <button onClick={checkStatus} className="btn-ghost btn-sm"><RefreshCw size={13} /> Refresh</button>
                <button onClick={handleDelete} disabled={loading} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg text-red-500 hover:bg-red-50 transition-all">
                  <Trash2 size={13} /> Cancel & Delete
                </button>
              </div>
            </div>
          )}

          {/* Disconnected */}
          {status === "disconnected" && (
            <div className="text-center space-y-6">
              <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto">
                <Smartphone size={28} className="text-gray-400" />
              </div>
              <div>
                <h2 className="text-lg font-bold mb-1">Connect Your WhatsApp</h2>
                <p className="text-sm text-gray-500 max-w-sm mx-auto">Reminders come from your clinic&apos;s own number. Patients see your name and photo.</p>
              </div>
              {error && <div className="p-2.5 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600 max-w-sm mx-auto">{error}</div>}
              <button onClick={handleConnect} disabled={loading} className="btn-primary px-8 py-3">
                {loading ? <><RefreshCw size={16} className="animate-spin" /> Connecting...</> : <><Smartphone size={16} /> Connect WhatsApp</>}
              </button>
              {/* Steps */}
              <div className="max-w-sm mx-auto text-left space-y-3 pt-2">
                {[
                  { n: 1, t: "Click 'Connect WhatsApp'", d: "A QR code appears" },
                  { n: 2, t: "Open WhatsApp → Linked Devices", d: "Tap 'Link a Device'" },
                  { n: 3, t: "Scan the QR code", d: "Point your camera at the code" },
                  { n: 4, t: "Done!", d: "Reminders send automatically" },
                ].map(s => (
                  <div key={s.n} className="flex items-start gap-3">
                    <div className="w-7 h-7 rounded-full bg-primary-600 text-white flex items-center justify-center text-xs font-bold shrink-0">{s.n}</div>
                    <div>
                      <p className="text-sm font-medium">{s.t}</p>
                      <p className="text-[11px] text-gray-400">{s.d}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Security */}
      <div className="card p-4 flex items-center gap-3 bg-primary-50 border-primary-100">
        <Shield size={16} className="text-primary-600 shrink-0" />
        <div className="flex-1">
          <p className="text-xs font-semibold text-primary-800">Security</p>
          <p className="text-[11px] text-primary-600">No credentials stored · QR-only auth · End-to-end encrypted · Disconnect anytime</p>
        </div>
      </div>

      {/* FAQ */}
      <div className="card overflow-hidden">
        <div className="px-5 py-3.5 border-b border-gray-50">
          <h3 className="text-sm font-bold">FAQ</h3>
        </div>
        {FAQ.map((item, i) => (
          <div key={i} className="border-b border-gray-50 last:border-0">
            <button onClick={() => setOpenFaq(openFaq === i ? null : i)} className="w-full flex items-center justify-between px-5 py-3 text-left hover:bg-gray-50/50 transition-colors">
              <span className="text-sm font-medium text-dark">{item.q}</span>
              {openFaq === i ? <ChevronUp size={14} className="text-gray-400 shrink-0" /> : <ChevronDown size={14} className="text-gray-400 shrink-0" />}
            </button>
            {openFaq === i && <p className="px-5 pb-3 text-sm text-gray-500 animate-fade-in">{item.a}</p>}
          </div>
        ))}
      </div>
    </div>
  );
}
