import { useState, useEffect } from "react";
import {
  Database,
  Download,
  Trash2,
  CheckCircle2,
  RefreshCw,
  HardDrive,
  Gamepad2,
  HeartPulse,
} from "lucide-react";
import { ActionButton, Card, Pill } from "../ui-kit";
import { offlineDB, GameRecord, YogaSessionRecord } from "@/lib/offline-db";

export function OfflineSqlViewer() {
  const [games, setGames] = useState<GameRecord[]>([]);
  const [yogaSessions, setYogaSessions] = useState<YogaSessionRecord[]>([]);
  const [activeTab, setActiveTab] = useState<"games" | "yoga">("games");
  const [loading, setLoading] = useState(true);

  const loadData = async () => {
    setLoading(true);
    const g = await offlineDB.getGameHistory();
    const y = await offlineDB.getYogaSessions();
    setGames(g);
    setYogaSessions(y);
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleExport = async () => {
    const data = await offlineDB.exportFullDatabase();
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `neurosaathi_offline_sql_${new Date().toISOString().split("T")[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleClear = async () => {
    if (confirm("Kya aap offline database clear karna chahte hain?")) {
      await offlineDB.clearAllTables();
      loadData();
    }
  };

  return (
    <Card className="p-4 bg-card border border-border shadow-sm space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className="grid h-8 w-8 place-items-center rounded-xl bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
            <Database className="h-4 w-4" />
          </div>
          <div>
            <h4 className="font-display text-sm font-bold flex items-center gap-1.5">
              Offline SQL Database
              <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-emerald-600 bg-emerald-500/15 px-2 py-0.5 rounded-full">
                <CheckCircle2 className="h-2.5 w-2.5" /> 100% Offline Ready
              </span>
            </h4>
            <p className="text-[11px] text-muted-foreground">
              {games.length} Game records · {yogaSessions.length} Yoga sessions
            </p>
          </div>
        </div>

        <div className="flex items-center gap-1.5">
          <button
            onClick={loadData}
            className="press p-2 rounded-xl border border-border bg-secondary/50 text-muted-foreground hover:text-foreground"
            title="Refresh tables"
          >
            <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          </button>
          <button
            onClick={handleExport}
            className="press p-2 rounded-xl border border-border bg-secondary/50 text-muted-foreground hover:text-foreground"
            title="Export JSON"
          >
            <Download className="h-3.5 w-3.5" />
          </button>
          <button
            onClick={handleClear}
            className="press p-2 rounded-xl border border-rose-500/20 text-rose-500 hover:bg-rose-500/10"
            title="Clear"
          >
            <Trash2 className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 border-b border-border/50 pb-2">
        <button
          onClick={() => setActiveTab("games")}
          className={`press flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold ${
            activeTab === "games"
              ? "gradient-primary text-primary-foreground"
              : "bg-secondary/40 text-muted-foreground"
          }`}
        >
          <Gamepad2 className="h-3.5 w-3.5" /> games_history ({games.length})
        </button>
        <button
          onClick={() => setActiveTab("yoga")}
          className={`press flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold ${
            activeTab === "yoga"
              ? "gradient-primary text-primary-foreground"
              : "bg-secondary/40 text-muted-foreground"
          }`}
        >
          <HeartPulse className="h-3.5 w-3.5" /> yoga_sessions ({yogaSessions.length})
        </button>
      </div>

      {/* Table Content */}
      <div className="max-h-48 overflow-y-auto rounded-2xl border border-border/60 bg-secondary/20 p-2 space-y-1.5 no-scrollbar text-xs">
        {activeTab === "games" ? (
          games.length === 0 ? (
            <p className="text-center text-muted-foreground py-4 text-xs">
              Koi game score abhi tak record nahi hua. Khelna shuru karein!
            </p>
          ) : (
            games.map((g) => (
              <div
                key={g.id}
                className="flex items-center justify-between p-2 rounded-xl bg-card border border-border/50 text-[11px]"
              >
                <div className="min-w-0 flex-1">
                  <p className="font-semibold truncate">{g.game_name}</p>
                  <p className="text-[10px] text-muted-foreground">
                    {new Date(g.completed_at).toLocaleTimeString([], {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}{" "}
                    · {g.moves} moves · {g.time_seconds}s
                  </p>
                </div>
                <div className="text-right pl-2">
                  <span className="font-bold text-primary">{g.score} pts</span>
                  <p className="text-[10px] text-emerald-600 font-mono">{g.difficulty}</p>
                </div>
              </div>
            ))
          )
        ) : yogaSessions.length === 0 ? (
          <p className="text-center text-muted-foreground py-4 text-xs">
            Koi yoga session abhi tak record nahi hua. AI Yoga shuru karein!
          </p>
        ) : (
          yogaSessions.map((y) => (
            <div
              key={y.id}
              className="flex items-center justify-between p-2 rounded-xl bg-card border border-border/50 text-[11px]"
            >
              <div className="min-w-0 flex-1">
                <p className="font-semibold truncate">{y.pose_name}</p>
                <p className="text-[10px] text-muted-foreground">
                  {new Date(y.timestamp).toLocaleTimeString([], {
                    hour: "2-digit",
                    minute: "2-digit",
                  })}{" "}
                  · {y.hold_duration_seconds}s hold
                </p>
              </div>
              <div className="text-right pl-2">
                <span className="font-bold text-emerald-600">{y.accuracy_avg}%</span>
                <p className="text-[10px] text-muted-foreground">{y.pose_category}</p>
              </div>
            </div>
          ))
        )}
      </div>
    </Card>
  );
}
