import { useState } from "react";
import { Radio, RefreshCw, Smartphone, CheckCircle2, AlertCircle } from "lucide-react";
import * as nfcApi from "../../../shared/api/nfc";

const SUPPORTED_CARDS = ["NTAG213", "NTAG215", "NTAG216", "MIFARE", "Ultralight", "DESFire"];

export default function TapNFCCard() {
  const [uid, setUid] = useState("");
  const [scanning, setScanning] = useState(false);
  const [lastScan, setLastScan] = useState(null);
  const [error, setError] = useState(null);

  const recordScan = async () => {
    const trimmed = uid.trim();
    if (!trimmed || scanning) return;
    setScanning(true);
    setError(null);
    try {
      const res = await nfcApi.recordScan({ uid: trimmed });
      setLastScan({ id: res.id, uid: trimmed, at: new Date() });
    } catch (e) {
      setError(e.message || "Scan failed");
      setLastScan(null);
    } finally {
      setScanning(false);
    }
  };

  const reset = () => {
    setUid("");
    setLastScan(null);
    setError(null);
  };

  const statusLabel = error ? "Scan Failed" : lastScan ? "Scan Recorded" : scanning ? "Recording…" : "Ready to Scan";
  const statusColor = error ? "text-red-600 bg-red-50 border-red-200" : lastScan ? "text-green-700 bg-green-50 border-green-200" : "text-red-600 bg-red-50 border-red-200";

  return (
    <div className="bg-white border border-red-100 rounded-xl p-4 shadow-sm">
      <h2 className="text-red-900 font-bold text-sm mb-0.5 flex items-center gap-2">
        <Radio className="w-4 h-4 text-red-500" />2. Tap Your NFC Card
      </h2>
      <p className="text-red-400 text-xs mb-4">Enter card UID and record a scan event via API</p>

      <div className="flex items-center gap-4 mb-4">
        <div className="relative w-24 h-24 flex-shrink-0">
          <div className={`absolute inset-0 rounded-full border-2 border-red-300/40 ${scanning ? "animate-ping" : ""}`} />
          <div className="absolute inset-2 rounded-full border-2 border-rose-300/30 animate-pulse" />
          <div className="absolute inset-3 rounded-full bg-red-50 border border-red-200 flex items-center justify-center shadow-inner">
            <Smartphone className="w-9 h-9 text-red-400" />
          </div>
        </div>
        <div className="flex-1 min-w-0">
          <div className={`flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1.5 rounded-full w-fit mb-3 border ${statusColor}`}>
            {lastScan ? <CheckCircle2 className="w-3.5 h-3.5" /> : error ? <AlertCircle className="w-3.5 h-3.5" /> : <div className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse flex-shrink-0" />}
            {statusLabel}
          </div>
          <p className="text-red-500 text-xs font-medium mb-1.5">Supported Cards</p>
          <div className="flex flex-wrap gap-1">
            {SUPPORTED_CARDS.map((c) => (
              <span key={c} className="text-[9px] text-red-600 bg-red-50 border border-red-200 px-1.5 py-0.5 rounded-md">{c}</span>
            ))}
          </div>
        </div>
      </div>

      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={uid}
          onChange={(e) => setUid(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && recordScan()}
          placeholder="Card UID (e.g. 04:A7:3B:9C)"
          className="flex-1 text-xs border border-red-200 rounded-lg px-3 py-2 text-red-900 placeholder:text-red-300 outline-none focus:border-red-400"
        />
        <button type="button" onClick={recordScan} disabled={scanning || !uid.trim()}
          className="px-3 py-2 text-xs font-semibold rounded-lg bg-red-600 text-white hover:bg-red-500 disabled:opacity-50 transition-colors">
          Record Scan
        </button>
      </div>

      <div className="border-t border-red-100 pt-3">
        <div className="flex items-center justify-between mb-2">
          <p className="text-red-900 text-xs font-semibold">Card Information</p>
          <button type="button" onClick={reset} className="text-red-400 hover:text-red-700 transition-colors"><RefreshCw className="w-3.5 h-3.5" /></button>
        </div>
        <div className="grid grid-cols-2 gap-x-4 gap-y-1.5">
          {[
            ["Status", error ? "Error" : lastScan ? "Recorded" : "No Card Detected"],
            ["UID", lastScan?.uid || (uid.trim() || "--")],
            ["Scan ID", lastScan?.id || "--"],
            ["Recorded", lastScan?.at ? lastScan.at.toLocaleTimeString() : "--"],
          ].map(([l, v]) => (
            <div key={l} className="flex items-center gap-1.5 text-xs">
              <span className="text-red-400 w-16 flex-shrink-0 text-[10px]">{l}</span>
              <span className={`text-[10px] truncate ${error ? "text-red-600" : "text-red-700"}`}>{v}</span>
            </div>
          ))}
        </div>
        {error && <p className="text-red-500 text-[10px] mt-2">{error}</p>}
      </div>
    </div>
  );
}
