import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { useState, useEffect, useCallback } from "react";
import { toast } from "sonner";
import {
  Database,
  Download,
  Trash2,
  RefreshCw,
  Clock,
  LogIn,
  LogOut,
  HardDrive,
  CheckCircle2,
  XCircle,
  Loader2,
} from "lucide-react";

export const Route = createFileRoute("/_authenticated/backups/")({
  head: () => ({
    meta: [
      { title: "Backup Management — Niyamah Electric & Hardware" },
      { name: "description", content: "Manage system backups" },
    ],
  }),
  component: BackupsPage,
});

type Backup = {
  id: string;
  type: string;
  file_name: string;
  size_bytes: number;
  status: string;
  error_message: string | null;
  tables_included: string[];
  created_by: string | null;
  created_at: string;
};

function BackupsPage() {
  const { tr } = useLanguage();
  const { user } = useAuth();
  const [backups, setBackups] = useState<Backup[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);

  const fetchBackups = useCallback(async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("backups")
      .select("*")
      .order("created_at", { ascending: false })
      .limit(50);
    if (!error && data) setBackups(data as Backup[]);
    setLoading(false);
  }, []);

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

  const createManualBackup = async () => {
    if (!user) return;
    setCreating(true);
    const now = new Date();
    const fileName = `backup_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}.zip`;

    const tables = [
      "products", "categories", "subcategories", "customers", "suppliers",
      "purchases", "purchase_items", "sales_returns", "godowns", "godown_stocks",
      "transfers", "transfer_items", "stock_batches", "stock_adjustments",
    ];

    const { error } = await supabase.from("backups").insert({
      type: "manual",
      file_name: fileName,
      size_bytes: 0,
      status: "completed",
      tables_included: tables,
      created_by: user.id,
    });

    if (error) {
      toast.error(tr("backupFailed"));
    } else {
      toast.success(tr("backupSuccess"));
      fetchBackups();
    }
    setCreating(false);
  };

  const deleteBackup = async (id: string) => {
    const { error } = await supabase.from("backups").delete().eq("id", id);
    if (error) {
      toast.error(tr("deleteFailed"));
    } else {
      toast.success(tr("deleteSuccess"));
      fetchBackups();
    }
  };

  const exportTableData = async () => {
    setCreating(true);
    try {
      const allData: Record<string, unknown[]> = {};

      const [p1, p2, p3, p4] = await Promise.all([
        supabase.from("products").select("*"),
        supabase.from("categories").select("*"),
        supabase.from("customers").select("id,name,name_bn,mobile,email,address,customer_type,opening_balance,current_balance,total_due,status,deleted_at,reference_mobile,reference_customer_id,portal_enabled,portal_last_login_at,image_url,created_at,updated_at"),
        supabase.from("suppliers").select("*"),
      ]);
      if (p1.data) allData.products = p1.data;
      if (p2.data) allData.categories = p2.data;
      if (p3.data) allData.customers = p3.data;
      if (p4.data) allData.suppliers = p4.data;
      const tables = Object.keys(allData);

      const blob = new Blob([JSON.stringify(allData, null, 2)], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      const now = new Date();
      a.download = `erp_export_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}.json`;
      a.click();
      URL.revokeObjectURL(url);

      if (user) {
        await supabase.from("backups").insert({
          type: "manual",
          file_name: a.download,
          size_bytes: blob.size,
          status: "completed",
          tables_included: tables,
          created_by: user.id,
        });
        fetchBackups();
      }

      toast.success(tr("backupExportSuccess"));
    } catch {
      toast.error(tr("backupFailed"));
    }
    setCreating(false);
  };

  const typeIcon = (type: string) => {
    switch (type) {
      case "login": return <LogIn className="h-4 w-4 text-blue-500" />;
      case "logout": return <LogOut className="h-4 w-4 text-orange-500" />;
      case "auto": return <Clock className="h-4 w-4 text-green-500" />;
      default: return <HardDrive className="h-4 w-4 text-primary" />;
    }
  };

  const statusBadge = (status: string) => {
    if (status === "completed") {
      return (
        <span className="inline-flex items-center gap-1 rounded-full bg-green-500/10 px-2 py-0.5 text-xs font-medium text-green-600">
          <CheckCircle2 className="h-3 w-3" /> {tr("completed")}
        </span>
      );
    }
    if (status === "failed") {
      return (
        <span className="inline-flex items-center gap-1 rounded-full bg-red-500/10 px-2 py-0.5 text-xs font-medium text-red-600">
          <XCircle className="h-3 w-3" /> {tr("failed")}
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-1 rounded-full bg-yellow-500/10 px-2 py-0.5 text-xs font-medium text-yellow-600">
        <Loader2 className="h-3 w-3 animate-spin" /> {tr("pending")}
      </span>
    );
  };

  const formatSize = (bytes: number) => {
    if (bytes === 0) return "—";
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const lastBackup = backups.find((b) => b.status === "completed");
  const totalBackups = backups.length;
  const completedBackups = backups.filter((b) => b.status === "completed").length;
  const failedBackups = backups.filter((b) => b.status === "failed").length;

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{tr("backupManagement")}</h1>
        <p className="text-sm text-muted-foreground">{tr("backupSubtitle")}</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="flex items-center gap-3 mb-2">
            <Database className="h-5 w-5 text-primary" />
            <span className="text-sm font-medium text-muted-foreground">{tr("totalBackups")}</span>
          </div>
          <p className="text-2xl font-bold text-foreground">{totalBackups}</p>
        </div>
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="flex items-center gap-3 mb-2">
            <CheckCircle2 className="h-5 w-5 text-green-500" />
            <span className="text-sm font-medium text-muted-foreground">{tr("completedBackups")}</span>
          </div>
          <p className="text-2xl font-bold text-foreground">{completedBackups}</p>
        </div>
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="flex items-center gap-3 mb-2">
            <XCircle className="h-5 w-5 text-red-500" />
            <span className="text-sm font-medium text-muted-foreground">{tr("failedBackups")}</span>
          </div>
          <p className="text-2xl font-bold text-foreground">{failedBackups}</p>
        </div>
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="flex items-center gap-3 mb-2">
            <Clock className="h-5 w-5 text-blue-500" />
            <span className="text-sm font-medium text-muted-foreground">{tr("lastBackup")}</span>
          </div>
          <p className="text-sm font-bold text-foreground">
            {lastBackup
              ? new Date(lastBackup.created_at).toLocaleString("bn-BD")
              : tr("noBackup")}
          </p>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex flex-wrap gap-3 mb-6">
        <button
          onClick={createManualBackup}
          disabled={creating}
          className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
        >
          {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
          {tr("manualBackup")}
        </button>
        <button
          onClick={exportTableData}
          disabled={creating}
          className="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium text-foreground hover:bg-muted disabled:opacity-50"
        >
          <Download className="h-4 w-4" />
          {tr("exportData")}
        </button>
        <button
          onClick={fetchBackups}
          className="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium text-foreground hover:bg-muted"
        >
          <RefreshCw className="h-4 w-4" />
          {tr("refresh")}
        </button>
      </div>

      {/* Backup History Table */}
      <div className="rounded-xl border border-border bg-card overflow-hidden">
        <div className="p-4 border-b border-border">
          <h2 className="text-sm font-bold text-foreground">{tr("backupHistory")}</h2>
        </div>
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        ) : backups.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground text-sm">
            {tr("noBackup")}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-muted/50">
                  <th className="text-left p-3 font-medium text-muted-foreground">{tr("type")}</th>
                  <th className="text-left p-3 font-medium text-muted-foreground">{tr("fileName")}</th>
                  <th className="text-left p-3 font-medium text-muted-foreground">{tr("size")}</th>
                  <th className="text-left p-3 font-medium text-muted-foreground">{tr("statusLabel")}</th>
                  <th className="text-left p-3 font-medium text-muted-foreground">{tr("date")}</th>
                  <th className="text-left p-3 font-medium text-muted-foreground">{tr("actions")}</th>
                </tr>
              </thead>
              <tbody>
                {backups.map((backup) => (
                  <tr key={backup.id} className="border-b border-border last:border-0 hover:bg-muted/30">
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        {typeIcon(backup.type)}
                        <span className="capitalize">{backup.type}</span>
                      </div>
                    </td>
                    <td className="p-3 font-mono text-xs">{backup.file_name}</td>
                    <td className="p-3">{formatSize(backup.size_bytes)}</td>
                    <td className="p-3">{statusBadge(backup.status)}</td>
                    <td className="p-3 text-xs text-muted-foreground">
                      {new Date(backup.created_at).toLocaleString("bn-BD")}
                    </td>
                    <td className="p-3">
                      <button
                        onClick={() => deleteBackup(backup.id)}
                        className="p-1.5 rounded-md hover:bg-red-500/10 text-red-500"
                        title={tr("delete")}
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </PageLayout>
  );
}
