import { createFileRoute } from "@tanstack/react-router";
import { useRef } from "react";
import { toast } from "sonner";
import { AppShell } from "@/components/layout/AppShell";
import { Button } from "@/components/ui/button";
import { Download, Upload, Trash2, Smartphone } from "lucide-react";
import {
  baixarCSV,
  csvParaLancamentos,
  lancamentosParaCSV,
} from "@/lib/csv";
import {
  importarLote,
  limparTudo,
  listarLancamentos,
} from "@/features/lancamentos/api/repo";

export const Route = createFileRoute("/configuracoes")({
  component: Configuracoes,
});

function Configuracoes() {
  const fileRef = useRef<HTMLInputElement>(null);

  async function exportar() {
    try {
      const items = await listarLancamentos();
      if (items.length === 0) {
        toast.info("Sem lançamentos para exportar");
        return;
      }
      baixarCSV(`fluxo_caixa_${new Date().toISOString().slice(0, 10)}.csv`, lancamentosParaCSV(items));
      toast.success(`${items.length} lançamento(s) exportado(s)`);
    } catch (err) {
      toast.error("Falha ao exportar", { description: String(err) });
    }
  }

  async function onImportFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    try {
      const text = await file.text();
      const { ok, erros } = csvParaLancamentos(text);
      if (ok.length > 0) await importarLote(ok);
      if (erros.length > 0) {
        toast.warning(`${ok.length} importado(s), ${erros.length} com erro`, {
          description: erros
            .slice(0, 3)
            .map((e) => `Linha ${e.linha}: ${e.mensagem}`)
            .join("\n"),
        });
      } else {
        toast.success(`${ok.length} lançamento(s) importado(s)`);
      }
    } catch (err) {
      toast.error("CSV inválido", { description: String(err) });
    }
  }

  async function onLimpar() {
    if (!confirm("Apagar TODOS os lançamentos? Esta ação não pode ser desfeita.")) return;
    try {
      await limparTudo();
      toast.success("Dados apagados");
    } catch (err) {
      toast.error("Falha ao limpar", { description: String(err) });
    }
  }

  return (
    <AppShell title="Configurações" subtitle="Backup e dados locais">
      <div className="space-y-4">
        <section className="rounded-2xl border border-border bg-card p-4">
          <h2 className="text-sm font-semibold text-foreground">Backup CSV</h2>
          <p className="mt-1 text-xs text-muted-foreground">
            Compatível com a versão Python (mesmo schema).
          </p>
          <div className="mt-3 flex flex-col gap-2">
            <Button onClick={exportar} variant="outline">
              <Download className="size-4" /> Exportar CSV
            </Button>
            <Button onClick={() => fileRef.current?.click()} variant="outline">
              <Upload className="size-4" /> Importar CSV
            </Button>
            <input
              ref={fileRef}
              type="file"
              accept=".csv,text/csv"
              className="hidden"
              onChange={onImportFile}
            />
          </div>
        </section>

        <section className="rounded-2xl border border-border bg-card p-4">
          <h2 className="text-sm font-semibold text-foreground">
            <Smartphone className="mr-1 inline size-4" /> Instalar no celular
          </h2>
          <p className="mt-1 text-xs text-muted-foreground">
            No Chrome (Android) ou Safari (iOS), toque no menu do navegador e escolha
            <strong> "Adicionar à tela inicial"</strong>. O app abrirá em tela cheia, com
            dados salvos localmente — funciona offline.
          </p>
        </section>

        <section className="rounded-2xl border border-destructive/30 bg-destructive/5 p-4">
          <h2 className="text-sm font-semibold text-destructive">Zona perigosa</h2>
          <p className="mt-1 text-xs text-muted-foreground">
            Apagar tudo remove permanentemente os dados deste dispositivo.
          </p>
          <Button onClick={onLimpar} variant="destructive" className="mt-3">
            <Trash2 className="size-4" /> Apagar todos os dados
          </Button>
        </section>

        <p className="pt-2 text-center text-xs text-muted-foreground">
          Caixa MEI · Nirlene Contabilidade
        </p>
      </div>
    </AppShell>
  );
}
