"use client";

import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { CategoryFilterCombobox } from "@/components/ui/category-filter-combobox";
import { AccountFilterCombobox } from "@/components/ui/account-filter-combobox";
import { CategoryIcon } from "@/components/ui/category-icon";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Calendar as CalendarComponent } from "@/components/ui/calendar";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";
import { Search, X, Filter, Wallet, Calendar } from "lucide-react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { useIsMobile } from "@/hooks/use-mobile";
import type { Account, Category, Folder, Transaction } from "@/lib/types";

type Period = "1month" | "3months" | "6months" | "12months" | "custom" | "all";

interface TransactionFiltersProps {
  searchQuery: string;
  onSearchChange: (query: string) => void;
  selectedAccounts: string[];
  onAccountsChange: (accounts: string[]) => void;
  selectedCategories: string[];
  onCategoriesChange: (categories: string[]) => void;
  showReconciled: string;
  onReconciledChange: (value: string) => void;
  period: Period;
  onPeriodChange: (period: Period) => void;
  customStartDate?: Date;
  customEndDate?: Date;
  onCustomStartDateChange: (date: Date | undefined) => void;
  onCustomEndDateChange: (date: Date | undefined) => void;
  isCustomDatePickerOpen: boolean;
  onCustomDatePickerOpenChange: (open: boolean) => void;
  accounts: Account[];
  folders: Folder[];
  categories: Category[];
  transactionsForAccountFilter?: Transaction[]; // Filtered by categories, search, reconciled, period (not accounts)
  transactionsForCategoryFilter?: Transaction[]; // Filtered by accounts, search, reconciled, period (not categories)
}

export function TransactionFilters({
  searchQuery,
  onSearchChange,
  selectedAccounts,
  onAccountsChange,
  selectedCategories,
  onCategoriesChange,
  showReconciled,
  onReconciledChange,
  period,
  onPeriodChange,
  customStartDate,
  customEndDate,
  onCustomStartDateChange,
  onCustomEndDateChange,
  isCustomDatePickerOpen,
  onCustomDatePickerOpenChange,
  accounts,
  folders,
  categories,
  transactionsForAccountFilter,
  transactionsForCategoryFilter,
}: TransactionFiltersProps) {
  const isMobile = useIsMobile();
  const [sheetOpen, setSheetOpen] = useState(false);

  const filtersContent = (
    <>
      <div className="flex flex-wrap gap-4">
        <div className="flex-1 min-w-[200px]">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="Rechercher..."
              value={searchQuery}
              onChange={(e) => onSearchChange(e.target.value)}
              className="pl-9"
            />
          </div>
        </div>

        <AccountFilterCombobox
          accounts={accounts}
          folders={folders}
          value={selectedAccounts}
          onChange={onAccountsChange}
          className="w-full md:w-[280px]"
          filteredTransactions={transactionsForAccountFilter}
        />

        <CategoryFilterCombobox
          categories={categories}
          value={selectedCategories}
          onChange={onCategoriesChange}
          className="w-full md:w-[220px]"
          filteredTransactions={transactionsForCategoryFilter}
        />

        <Select value={showReconciled} onValueChange={onReconciledChange}>
          <SelectTrigger className="w-full md:w-[160px]">
            <SelectValue placeholder="Pointage" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tout</SelectItem>
            <SelectItem value="reconciled">Pointées</SelectItem>
            <SelectItem value="not-reconciled">Non pointées</SelectItem>
          </SelectContent>
        </Select>

        <Select
          value={period}
          onValueChange={(v) => {
            onPeriodChange(v as Period);
            if (v !== "custom") {
              onCustomDatePickerOpenChange(false);
            } else {
              onCustomDatePickerOpenChange(true);
            }
          }}
        >
          <SelectTrigger className="w-full md:w-[150px]">
            <SelectValue placeholder="Période" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="1month">1 mois</SelectItem>
            <SelectItem value="3months">3 mois</SelectItem>
            <SelectItem value="6months">6 mois</SelectItem>
            <SelectItem value="12months">12 mois</SelectItem>
            <SelectItem value="custom">Personnalisé</SelectItem>
            <SelectItem value="all">Tout</SelectItem>
          </SelectContent>
        </Select>

        {period === "custom" && (
          <Popover
            open={isCustomDatePickerOpen}
            onOpenChange={onCustomDatePickerOpenChange}
          >
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                className="w-full md:w-[280px] justify-start text-left font-normal"
              >
                <Calendar className="mr-2 h-4 w-4" />
                {customStartDate && customEndDate ? (
                  <>
                    {format(customStartDate, "PPP", { locale: fr })} -{" "}
                    {format(customEndDate, "PPP", { locale: fr })}
                  </>
                ) : customStartDate ? (
                  format(customStartDate, "PPP", { locale: fr })
                ) : (
                  <span className="text-muted-foreground">
                    Sélectionner les dates
                  </span>
                )}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
              <div className="p-4 space-y-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Date de début</label>
                  <CalendarComponent
                    mode="single"
                    selected={customStartDate}
                    onSelect={(date) => {
                      onCustomStartDateChange(date);
                      if (date && customEndDate && date > customEndDate) {
                        onCustomEndDateChange(undefined);
                      }
                    }}
                    locale={fr}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Date de fin</label>
                  <CalendarComponent
                    mode="single"
                    selected={customEndDate}
                    onSelect={(date) => {
                      if (date && customStartDate && date < customStartDate) {
                        return;
                      }
                      onCustomEndDateChange(date);
                      if (date && customStartDate) {
                        onCustomDatePickerOpenChange(false);
                      }
                    }}
                    disabled={(date) => {
                      if (!customStartDate) return true;
                      return date < customStartDate;
                    }}
                    locale={fr}
                  />
                </div>
                {customStartDate && customEndDate && (
                  <div className="flex gap-2 pt-2 border-t">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => {
                        onCustomStartDateChange(undefined);
                        onCustomEndDateChange(undefined);
                      }}
                    >
                      Réinitialiser
                    </Button>
                    <Button
                      size="sm"
                      className="flex-1"
                      onClick={() => onCustomDatePickerOpenChange(false)}
                    >
                      Valider
                    </Button>
                  </div>
                )}
              </div>
            </PopoverContent>
          </Popover>
        )}
      </div>

      <ActiveFilters
        searchQuery={searchQuery}
        onClearSearch={() => onSearchChange("")}
        selectedAccounts={selectedAccounts}
        onRemoveAccount={(id) => {
          const newAccounts = selectedAccounts.filter((a) => a !== id);
          onAccountsChange(newAccounts.length > 0 ? newAccounts : ["all"]);
        }}
        onClearAccounts={() => onAccountsChange(["all"])}
        selectedCategories={selectedCategories}
        onRemoveCategory={(id) => {
          const newCategories = selectedCategories.filter((c) => c !== id);
          onCategoriesChange(
            newCategories.length > 0 ? newCategories : ["all"],
          );
        }}
        onClearCategories={() => onCategoriesChange(["all"])}
        showReconciled={showReconciled}
        onClearReconciled={() => onReconciledChange("all")}
        period={period}
        onClearPeriod={() => {
          onPeriodChange("all");
          onCustomStartDateChange(undefined);
          onCustomEndDateChange(undefined);
        }}
        customStartDate={customStartDate}
        customEndDate={customEndDate}
        accounts={accounts}
        categories={categories}
      />
    </>
  );

  if (isMobile) {
    const activeFiltersCount =
      (searchQuery.trim() !== "" ? 1 : 0) +
      (!selectedAccounts.includes("all") ? selectedAccounts.length : 0) +
      (!selectedCategories.includes("all") ? selectedCategories.length : 0) +
      (showReconciled !== "all" ? 1 : 0) +
      (period !== "all" ? 1 : 0);

    return (
      <>
        <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
          <SheetTrigger asChild>
            <Button variant="outline" className="w-full">
              <Filter className="w-4 h-4 mr-2" />
              Filtres
              {activeFiltersCount > 0 && (
                <Badge variant="secondary" className="ml-2">
                  {activeFiltersCount}
                </Badge>
              )}
            </Button>
          </SheetTrigger>
          <SheetContent
            side="bottom"
            className="h-[85vh] overflow-y-auto px-4 pb-6"
          >
            <SheetHeader className="px-0">
              <SheetTitle>Filtres</SheetTitle>
            </SheetHeader>
            <div className="mt-6 space-y-4 px-0">{filtersContent}</div>
          </SheetContent>
        </Sheet>
      </>
    );
  }

  return (
    <Card>
      <CardContent className="pt-4">{filtersContent}</CardContent>
    </Card>
  );
}

function ActiveFilters({
  searchQuery,
  onClearSearch,
  selectedAccounts,
  onRemoveAccount,
  onClearAccounts,
  selectedCategories,
  onRemoveCategory,
  onClearCategories,
  showReconciled,
  onClearReconciled,
  period,
  onClearPeriod,
  customStartDate,
  customEndDate,
  accounts,
  categories,
}: {
  searchQuery: string;
  onClearSearch: () => void;
  selectedAccounts: string[];
  onRemoveAccount: (id: string) => void;
  onClearAccounts: () => void;
  selectedCategories: string[];
  onRemoveCategory: (id: string) => void;
  onClearCategories: () => void;
  showReconciled: string;
  onClearReconciled: () => void;
  period: Period;
  onClearPeriod: () => void;
  customStartDate?: Date;
  customEndDate?: Date;
  accounts: Account[];
  categories: Category[];
}) {
  const hasSearch = searchQuery.trim() !== "";
  const hasAccounts = !selectedAccounts.includes("all");
  const hasCategories = !selectedCategories.includes("all");
  const hasReconciled = showReconciled !== "all";
  const hasPeriod = period !== "all";

  const hasActiveFilters =
    hasSearch || hasAccounts || hasCategories || hasReconciled || hasPeriod;

  if (!hasActiveFilters) return null;

  const selectedAccs = accounts.filter((a) => selectedAccounts.includes(a.id));
  const selectedCats = categories.filter((c) =>
    selectedCategories.includes(c.id),
  );
  const isUncategorized = selectedCategories.includes("uncategorized");

  const clearAll = () => {
    onClearSearch();
    onClearAccounts();
    onClearCategories();
    onClearReconciled();
    onClearPeriod();
  };

  return (
    <div className="flex items-center gap-2 mt-3 pt-3 border-t border-border flex-wrap">
      <Filter className="h-3.5 w-3.5 text-muted-foreground" />

      {hasSearch && (
        <Badge variant="secondary" className="gap-1 text-xs font-normal">
          Recherche: &quot;{searchQuery}&quot;
          <button
            onClick={onClearSearch}
            className="ml-1 hover:text-foreground"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      )}

      {selectedAccs.map((acc) => (
        <Badge
          key={acc.id}
          variant="secondary"
          className="gap-1 text-xs font-normal"
        >
          <Wallet className="h-3 w-3" />
          {acc.name}
          <button
            onClick={() => onRemoveAccount(acc.id)}
            className="ml-1 hover:text-foreground"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      ))}

      {isUncategorized && (
        <Badge variant="secondary" className="gap-1 text-xs font-normal">
          Non catégorisé
          <button
            onClick={onClearCategories}
            className="ml-1 hover:text-foreground"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      )}

      {selectedCats.map((cat) => (
        <Badge
          key={cat.id}
          variant="secondary"
          className="gap-1 text-xs font-normal"
          style={{
            backgroundColor: `${cat.color}15`,
            borderColor: `${cat.color}30`,
          }}
        >
          <CategoryIcon icon={cat.icon} color={cat.color} size={12} />
          {cat.name}
          <button
            onClick={() => onRemoveCategory(cat.id)}
            className="ml-1 hover:text-foreground"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      ))}

      {hasReconciled && (
        <Badge variant="secondary" className="gap-1 text-xs font-normal">
          {showReconciled === "reconciled" ? "Pointées" : "Non pointées"}
          <button
            onClick={onClearReconciled}
            className="ml-1 hover:text-foreground"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      )}

      {hasPeriod && (
        <Badge variant="secondary" className="gap-1 text-xs font-normal">
          <Calendar className="h-3 w-3" />
          {period === "custom" && customStartDate && customEndDate
            ? `${format(customStartDate, "d MMM", { locale: fr })} - ${format(customEndDate, "d MMM yyyy", { locale: fr })}`
            : period === "1month"
              ? "1 mois"
              : period === "3months"
                ? "3 mois"
                : period === "6months"
                  ? "6 mois"
                  : period === "12months"
                    ? "12 mois"
                    : "Période"}
          <button
            onClick={onClearPeriod}
            className="ml-1 hover:text-foreground"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      )}

      <button
        onClick={clearAll}
        className="text-xs text-muted-foreground hover:text-foreground ml-auto"
      >
        Effacer tout
      </button>
    </div>
  );
}
