"use client"

import { useState } from "react"
import { Sidebar } from "@/components/dashboard/sidebar"
import { useBankingData } from "@/lib/hooks"
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 { Badge } from "@/components/ui/badge"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Plus, MoreVertical, Pencil, Trash2, Tag, RefreshCw, X } from "lucide-react"
import { generateId, autoCategorize, addCategory, updateCategory, deleteCategory } from "@/lib/store-db"
import type { Category } from "@/lib/types"
import { cn } from "@/lib/utils"

const categoryColors = [
  "#22c55e",
  "#3b82f6",
  "#f59e0b",
  "#ec4899",
  "#ef4444",
  "#8b5cf6",
  "#06b6d4",
  "#84cc16",
  "#f97316",
  "#6366f1",
]

export default function CategoriesPage() {
  const { data, isLoading, refresh } = useBankingData()
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [editingCategory, setEditingCategory] = useState<Category | null>(null)
  const [formData, setFormData] = useState({
    name: "",
    color: "#22c55e",
    keywords: [] as string[],
  })
  const [newKeyword, setNewKeyword] = useState("")

  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 getCategoryStats = (categoryId: string) => {
    const categoryTransactions = data.transactions.filter((t) => t.categoryId === categoryId)
    const total = categoryTransactions.reduce((sum, t) => sum + Math.abs(t.amount), 0)
    const count = categoryTransactions.length
    return { total, count }
  }

  const handleNewCategory = () => {
    setEditingCategory(null)
    setFormData({ name: "", color: "#22c55e", keywords: [] })
    setIsDialogOpen(true)
  }

  const handleEdit = (category: Category) => {
    setEditingCategory(category)
    setFormData({
      name: category.name,
      color: category.color,
      keywords: [...category.keywords],
    })
    setIsDialogOpen(true)
  }

  const handleSave = async () => {
    try {
      if (editingCategory) {
        await updateCategory({
          ...editingCategory,
          name: formData.name,
          color: formData.color,
          keywords: formData.keywords,
        })
      } else {
        await addCategory({
          name: formData.name,
          color: formData.color,
          keywords: formData.keywords,
          icon: "tag",
          parentId: null,
        })
      }
      refresh()
      setIsDialogOpen(false)
    } catch (error) {
      console.error("Error saving category:", error)
      alert("Erreur lors de la sauvegarde de la catégorie")
    }
  }

  const handleDelete = async (categoryId: string) => {
    if (!confirm("Supprimer cette catégorie ?")) return

    try {
      await deleteCategory(categoryId)
      refresh()
    } catch (error) {
      console.error("Error deleting category:", error)
      alert("Erreur lors de la suppression de la catégorie")
    }
  }

  const addKeyword = () => {
    if (newKeyword.trim() && !formData.keywords.includes(newKeyword.trim().toLowerCase())) {
      setFormData({
        ...formData,
        keywords: [...formData.keywords, newKeyword.trim().toLowerCase()],
      })
      setNewKeyword("")
    }
  }

  const removeKeyword = (keyword: string) => {
    setFormData({
      ...formData,
      keywords: formData.keywords.filter((k) => k !== keyword),
    })
  }

  const reApplyAutoCategories = async () => {
    if (!confirm("Recatégoriser automatiquement les transactions non catégorisées ?")) return

    try {
      const { updateTransaction } = await import("@/lib/store-db")
      const uncategorized = data.transactions.filter((t) => !t.categoryId)
      
      for (const transaction of uncategorized) {
        const categoryId = autoCategorize(transaction.description + " " + (transaction.memo || ""), data.categories)
        if (categoryId) {
          await updateTransaction({ ...transaction, categoryId })
        }
      }
      refresh()
    } catch (error) {
      console.error("Error re-categorizing:", error)
      alert("Erreur lors de la recatégorisation")
    }
  }

  const uncategorizedCount = data.transactions.filter((t) => !t.categoryId).length

  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">Catégories</h1>
              <p className="text-muted-foreground">
                Gérez vos catégories et mots-clés pour la catégorisation automatique
              </p>
            </div>
            <div className="flex gap-2">
              {uncategorizedCount > 0 && (
                <Button variant="outline" onClick={reApplyAutoCategories}>
                  Recatégoriser ({uncategorizedCount})
                </Button>
              )}
              <Button onClick={handleNewCategory}>
                <Plus className="w-4 h-4 mr-2" />
                Nouvelle catégorie
              </Button>
            </div>
          </div>

          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {data.categories.map((category) => {
              const stats = getCategoryStats(category.id)

              return (
                <Card key={category.id}>
                  <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 flex items-center justify-center"
                          style={{ backgroundColor: `${category.color}20` }}
                        >
                          <Tag className="w-5 h-5" style={{ color: category.color }} />
                        </div>
                        <div>
                          <CardTitle className="text-base">{category.name}</CardTitle>
                          <p className="text-xs text-muted-foreground">
                            {stats.count} transaction{stats.count > 1 ? "s" : ""}
                          </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(category)}>
                            <Pencil className="w-4 h-4 mr-2" />
                            Modifier
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleDelete(category.id)} className="text-red-600">
                            <Trash2 className="w-4 h-4 mr-2" />
                            Supprimer
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="text-lg font-semibold mb-3">{formatCurrency(stats.total)}</div>
                    <div className="flex flex-wrap gap-1">
                      {category.keywords.slice(0, 5).map((keyword) => (
                        <Badge key={keyword} variant="secondary" className="text-xs">
                          {keyword}
                        </Badge>
                      ))}
                      {category.keywords.length > 5 && (
                        <Badge variant="secondary" className="text-xs">
                          +{category.keywords.length - 5}
                        </Badge>
                      )}
                    </div>
                  </CardContent>
                </Card>
              )
            })}
          </div>
        </div>
      </main>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{editingCategory ? "Modifier la catégorie" : "Nouvelle catégorie"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Nom</Label>
              <Input
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="Ex: Alimentation"
              />
            </div>

            <div className="space-y-2">
              <Label>Couleur</Label>
              <div className="flex flex-wrap gap-2">
                {categoryColors.map((color) => (
                  <button
                    key={color}
                    onClick={() => setFormData({ ...formData, color })}
                    className={cn(
                      "w-8 h-8 rounded-full transition-transform",
                      formData.color === color && "ring-2 ring-offset-2 ring-primary scale-110",
                    )}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>

            <div className="space-y-2">
              <Label>Mots-clés pour la catégorisation automatique</Label>
              <div className="flex gap-2">
                <Input
                  value={newKeyword}
                  onChange={(e) => setNewKeyword(e.target.value)}
                  placeholder="Ajouter un mot-clé"
                  onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addKeyword())}
                />
                <Button type="button" onClick={addKeyword} size="icon">
                  <Plus className="w-4 h-4" />
                </Button>
              </div>
              <div className="flex flex-wrap gap-1 mt-2">
                {formData.keywords.map((keyword) => (
                  <Badge key={keyword} variant="secondary" className="gap-1">
                    {keyword}
                    <button onClick={() => removeKeyword(keyword)}>
                      <X className="w-3 h-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                Annuler
              </Button>
              <Button onClick={handleSave} disabled={!formData.name.trim()}>
                {editingCategory ? "Enregistrer" : "Créer"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
