"use client";

import { useState } from "react";
import { PageLayout, LoadingState, PageHeader } from "@/components/layout";
import {
  DataCard,
  DangerZoneCard,
  OFXInfoCard,
  BackupCard,
  PasswordCard,
  ReconcileDateRangeCard,
  BackgroundCard,
  ThemeCard,
} from "@/components/settings";
import { useBankingData } from "@/lib/hooks";
import type { BankingData } from "@/lib/types";

export default function SettingsPage() {
  const { data, isLoading, refresh, update } = useBankingData();
  const [importing, setImporting] = useState(false);

  if (isLoading || !data) {
    return <LoadingState />;
  }

  const exportData = () => {
    const dataStr = JSON.stringify(data, null, 2);
    const blob = new Blob([dataStr], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `fintrack-backup-${new Date().toISOString().split("T")[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const importData = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".json";
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      setImporting(true);
      try {
        const content = await file.text();
        const importedData = JSON.parse(content) as BankingData;

        if (
          !importedData.accounts ||
          !importedData.transactions ||
          !importedData.categories ||
          !importedData.folders
        ) {
          alert("Format de fichier invalide");
          return;
        }

        update(importedData);
        alert("Données importées avec succès");
      } catch {
        alert("Erreur lors de l'import");
      } finally {
        setImporting(false);
      }
    };
    input.click();
  };

  const resetData = () => {
    localStorage.removeItem("banking-app-data");
    window.location.reload();
  };

  const clearAllCategories = async () => {
    try {
      const response = await fetch(
        "/api/banking/transactions/clear-categories",
        {
          method: "POST",
        },
      );
      if (!response.ok) throw new Error("Erreur");
      refresh();
      alert("Catégories supprimées de toutes les opérations");
    } catch (error) {
      console.error(error);
      alert("Erreur lors de la suppression des catégories");
    }
  };

  const deduplicateTransactions = async () => {
    try {
      const response = await fetch("/api/banking/transactions/deduplicate", {
        method: "POST",
      });
      if (!response.ok) throw new Error("Erreur");
      const result = await response.json();
      refresh();
      return result;
    } catch (error) {
      console.error(error);
      throw error;
    }
  };

  const categorizedCount = data.transactions.filter((t) => t.categoryId).length;

  return (
    <PageLayout>
      <div className="max-w-2xl space-y-6">
        <PageHeader
          title="Paramètres"
          description="Gérez vos données et préférences"
        />

        <DataCard
          data={data}
          importing={importing}
          onExport={exportData}
          onImport={importData}
        />

        <BackupCard />

        <PasswordCard />

        <ThemeCard />

        <BackgroundCard />

        <ReconcileDateRangeCard />

        <DangerZoneCard
          categorizedCount={categorizedCount}
          onClearCategories={clearAllCategories}
          onResetData={resetData}
          onDeduplicate={deduplicateTransactions}
        />

        <OFXInfoCard />
      </div>
    </PageLayout>
  );
}
