"use client";

import { useState } from "react";
import { Sidebar } from "@/components/dashboard/sidebar";
import { useBankingData } from "@/lib/hooks";
import { updateAccount, deleteAccount } from "@/lib/store-db";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  MoreVertical,
  Pencil,
  Trash2,
  Building2,
  CreditCard,
  Wallet,
  PiggyBank,
  RefreshCw,
  ExternalLink,
} from "lucide-react";
import type { Account } from "@/lib/types";
import { cn } from "@/lib/utils";

const accountTypeIcons = {
  CHECKING: Wallet,
  SAVINGS: PiggyBank,
  CREDIT_CARD: CreditCard,
  OTHER: Building2,
};

const accountTypeLabels = {
  CHECKING: "Compte courant",
  SAVINGS: "Épargne",
  CREDIT_CARD: "Carte de crédit",
  OTHER: "Autre",
};

export default function AccountsPage() {
  const { data, isLoading, refresh } = useBankingData();
  const [editingAccount, setEditingAccount] = useState<Account | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    type: "CHECKING" as Account["type"],
    folderId: "folder-root",
    externalUrl: "",
  });

  if (isLoading || !data) {
    return (
      <div className="flex h-screen">
        <Sidebar />
        <main className="flex-1 flex items-center justify-center">
          <RefreshCw className="w-8 h-8 animate-spin text-muted-foreground" />
        </main>
      </div>
    );
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("fr-FR", {
      style: "currency",
      currency: "EUR",
    }).format(amount);
  };

  const handleEdit = (account: Account) => {
    setEditingAccount(account);
    setFormData({
      name: account.name,
      type: account.type,
      folderId: account.folderId || "folder-root",
      externalUrl: account.externalUrl || "",
    });
    setIsDialogOpen(true);
  };

  const handleSave = async () => {
    if (!editingAccount) return;

    try {
      const updatedAccount = {
        ...editingAccount,
        name: formData.name,
        type: formData.type,
        folderId: formData.folderId,
        externalUrl: formData.externalUrl || null,
      };
      await updateAccount(updatedAccount);
      refresh();
      setIsDialogOpen(false);
      setEditingAccount(null);
    } catch (error) {
      console.error("Error updating account:", error);
      alert("Erreur lors de la mise à jour du compte");
    }
  };

  const handleDelete = async (accountId: string) => {
    if (!confirm("Supprimer ce compte et toutes ses transactions ?")) return;

    try {
      await deleteAccount(accountId);
      refresh();
    } catch (error) {
      console.error("Error deleting account:", error);
      alert("Erreur lors de la suppression du compte");
    }
  };

  const getTransactionCount = (accountId: string) => {
    return data.transactions.filter((t) => t.accountId === accountId).length;
  };

  const totalBalance = data.accounts.reduce((sum, a) => sum + a.balance, 0);

  return (
    <div className="flex h-screen bg-background">
      <Sidebar />
      <main className="flex-1 overflow-auto">
        <div className="p-6 space-y-6">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-foreground">Comptes</h1>
              <p className="text-muted-foreground">
                Gérez vos comptes bancaires
              </p>
            </div>
            <div className="text-right">
              <p className="text-sm text-muted-foreground">Solde total</p>
              <p
                className={cn(
                  "text-2xl font-bold",
                  totalBalance >= 0 ? "text-emerald-600" : "text-red-600",
                )}
              >
                {formatCurrency(totalBalance)}
              </p>
            </div>
          </div>

          {data.accounts.length === 0 ? (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12">
                <Building2 className="w-16 h-16 text-muted-foreground mb-4" />
                <h3 className="text-lg font-semibold mb-2">Aucun compte</h3>
                <p className="text-muted-foreground text-center mb-4">
                  Importez un fichier OFX depuis le tableau de bord pour ajouter
                  votre premier compte.
                </p>
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {data.accounts.map((account) => {
                const Icon = accountTypeIcons[account.type];
                const folder = data.folders.find(
                  (f) => f.id === account.folderId,
                );

                return (
                  <Card key={account.id} className="relative">
                    <CardHeader className="pb-2">
                      <div className="flex items-start justify-between">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                            <Icon className="w-5 h-5 text-primary" />
                          </div>
                          <div>
                            <CardTitle className="text-base">
                              {account.name}
                            </CardTitle>
                            <p className="text-xs text-muted-foreground">
                              {accountTypeLabels[account.type]}
                            </p>
                          </div>
                        </div>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8"
                            >
                              <MoreVertical className="w-4 h-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => handleEdit(account)}
                            >
                              <Pencil className="w-4 h-4 mr-2" />
                              Modifier
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleDelete(account.id)}
                              className="text-red-600"
                            >
                              <Trash2 className="w-4 h-4 mr-2" />
                              Supprimer
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div
                        className={cn(
                          "text-2xl font-bold mb-2",
                          account.balance >= 0
                            ? "text-emerald-600"
                            : "text-red-600",
                        )}
                      >
                        {formatCurrency(account.balance)}
                      </div>
                      <div className="flex items-center justify-between text-sm text-muted-foreground">
                        <span>
                          {getTransactionCount(account.id)} transactions
                        </span>
                        {folder && <span>{folder.name}</span>}
                      </div>
                      {account.lastImport && (
                        <p className="text-xs text-muted-foreground mt-2">
                          Dernier import:{" "}
                          {new Date(account.lastImport).toLocaleDateString(
                            "fr-FR",
                          )}
                        </p>
                      )}
                      {account.externalUrl && (
                        <a
                          href={account.externalUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2"
                        >
                          <ExternalLink className="w-3 h-3" />
                          Accéder au portail banque
                        </a>
                      )}
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </div>
      </main>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Modifier le compte</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Nom du compte</Label>
              <Input
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Type de compte</Label>
              <Select
                value={formData.type}
                onValueChange={(v) =>
                  setFormData({ ...formData, type: v as Account["type"] })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {Object.entries(accountTypeLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>
                      {label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Dossier</Label>
              <Select
                value={formData.folderId}
                onValueChange={(v) => setFormData({ ...formData, folderId: v })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {data.folders.map((folder) => (
                    <SelectItem key={folder.id} value={folder.id}>
                      {folder.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Lien externe (portail banque)</Label>
              <Input
                value={formData.externalUrl}
                onChange={(e) =>
                  setFormData({ ...formData, externalUrl: e.target.value })
                }
                placeholder="https://..."
              />
              <p className="text-xs text-muted-foreground">
                URL personnalisée vers le portail de votre banque
              </p>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                Annuler
              </Button>
              <Button onClick={handleSave}>Enregistrer</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
