import { useState } from "react";
import { useLiveQuery } from "dexie-react-hooks";
import * as Icons from "lucide-react";
import { Upload, Trash2, FileDown, Puzzle } from "lucide-react";
import { db } from "../database/db";
import { useProfileStore } from "../stores/profileStore";
import { parseImportedGame } from "../utils/gameImportAdapter";
import { ImportedGameDefinition } from "../types/gameImport";
import { Card, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";
import { PageHeader } from "../components/PageHeader";
import { motion } from "framer-motion";

const TEMPLATE: ImportedGameDefinition = {
  schemaVersion: 1,
  id: "mon-jeu",
  name: "Mon Jeu",
  minPlayers: 2,
  maxPlayers: 6,
  scoreType: "negative",
  scoreFormula: { strategy: "sum_rounds" },
  targetScore: { type: "fixed", value: 100 },
  targetScoreCondition: "reaches",
  description:
    "Le score le plus bas gagne. La partie s'arrête quand un joueur atteint 100 points.",
  colors: { primary: "#3b82f6" },
};

export default function ImportedGames() {
  const activeProfileId = useProfileStore((s) => s.activeProfileId);
  const [feedback, setFeedback] = useState<
    { type: "ok" | "err"; message: string } | null
  >(null);

  const importedGames = useLiveQuery(
    async () => {
      if (!activeProfileId) return [];
      return db.importedGames
        .where("profileId")
        .equals(activeProfileId)
        .toArray();
    },
    [activeProfileId],
  );

  const handleImport = () => {
    setFeedback(null);
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "application/json,.json";
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file || !activeProfileId) return;
      try {
        const text = await file.text();
        const def = parseImportedGame(text);
        const existing = await db.importedGames.get([activeProfileId, def.id]);
        const now = Date.now();
        await db.importedGames.put({
          ...def,
          profileId: activeProfileId,
          createdAt: existing?.createdAt ?? now,
          updatedAt: now,
        });
        setFeedback({
          type: "ok",
          message: existing
            ? `« ${def.name} » mis à jour.`
            : `« ${def.name} » importé !`,
        });
      } catch (err) {
        setFeedback({
          type: "err",
          message: err instanceof Error ? err.message : "Import impossible.",
        });
      }
    };
    input.click();
  };

  const handleDelete = async (id: string, name: string) => {
    if (!activeProfileId) return;
    if (window.confirm(`Supprimer le jeu importé « ${name} » ?`)) {
      await db.importedGames.delete([activeProfileId, id]);
    }
  };

  const handleDownloadTemplate = () => {
    const blob = new Blob([JSON.stringify(TEMPLATE, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "skori-jeu-modele.json";
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="p-5 space-y-5 relative z-10">
      <PageHeader title="Jeux importés" />

      <p className="text-sm text-muted-foreground px-2">
        Ajoutez de nouveaux jeux à l'app via un fichier de définition JSON
        (icône, règles de score, options). Les jeux importés sont propres à ce
        profil.
      </p>

      {feedback && (
        <p
          className={`text-sm font-medium rounded-xl p-3 ${
            feedback.type === "ok"
              ? "text-emerald-700 bg-emerald-500/10"
              : "text-destructive bg-destructive/10"
          }`}
        >
          {feedback.message}
        </p>
      )}

      <div className="grid grid-cols-2 gap-3">
        <Button
          className="h-14 rounded-2xl font-black"
          onClick={handleImport}
        >
          <Upload className="w-5 h-5 mr-2" />
          Importer
        </Button>
        <Button
          variant="outline"
          className="h-14 rounded-2xl font-bold"
          onClick={handleDownloadTemplate}
        >
          <FileDown className="w-5 h-5 mr-2" />
          Modèle
        </Button>
      </div>

      <div className="space-y-3">
        {!importedGames || importedGames.length === 0 ? (
          <div className="text-center text-muted-foreground py-12 flex flex-col items-center bg-background/60 backdrop-blur-sm rounded-[2rem]">
            <Puzzle className="w-16 h-16 mb-4 opacity-20" />
            <p className="font-bold text-lg">Aucun jeu importé.</p>
            <p className="text-sm mt-1 max-w-[260px]">
              Téléchargez le modèle pour voir le format attendu.
            </p>
          </div>
        ) : (
          importedGames.map((game, index) => {
            const Icon = game.iconImage
              ? null
              : (Icons as any)["Puzzle"];
            return (
              <motion.div
                key={game.id}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: index * 0.05 }}
              >
                <Card className="border-0 shadow-lg bg-background/90 backdrop-blur-md">
                  <CardContent className="p-4 flex items-center justify-between">
                    <div className="flex items-center min-w-0">
                      <div
                        className="w-12 h-12 rounded-2xl flex items-center justify-center mr-3 shrink-0 overflow-hidden shadow-sm"
                        style={{ backgroundColor: `${game.colors.primary}20` }}
                      >
                        {game.iconImage ? (
                          <img
                            src={game.iconImage}
                            alt={game.name}
                            className="w-full h-full object-cover"
                          />
                        ) : Icon ? (
                          <Icon
                            className="w-6 h-6"
                            style={{ color: game.colors.primary }}
                          />
                        ) : null}
                      </div>
                      <div className="min-w-0">
                        <p className="font-black text-lg truncate">
                          {game.name}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {game.minPlayers}–{game.maxPlayers} joueurs
                        </p>
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDelete(game.id, game.name)}
                      className="text-destructive hover:bg-destructive/10 shrink-0"
                    >
                      <Trash2 className="w-5 h-5" />
                    </Button>
                  </CardContent>
                </Card>
              </motion.div>
            );
          })
        )}
      </div>
    </div>
  );
}
