"use client";

import { type SavedSearch } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Bookmark, BookmarkPlus, Trash2 } from "lucide-react";

interface SearchFilterBarProps {
  query: string;
  setQuery: (v: string) => void;
  fromFilter: string;
  setFromFilter: (v: string) => void;
  toFilter: string;
  setToFilter: (v: string) => void;
  dateFrom: string;
  setDateFrom: (v: string) => void;
  dateTo: string;
  setDateTo: (v: string) => void;
  sort: string;
  setSort: (v: string) => void;
  hasAttachment: boolean | undefined;
  setHasAttachment: (v: boolean | undefined) => void;
  searching: boolean;
  onSubmit: (e: React.FormEvent) => void;
  onOpenUpload: () => void;
  // Saved searches
  hasActiveSearch: boolean;
  savePopoverOpen: boolean;
  setSavePopoverOpen: (v: boolean) => void;
  saveName: string;
  setSaveName: (v: string) => void;
  saving: boolean;
  onSaveSearch: () => void;
  savedListOpen: boolean;
  setSavedListOpen: (v: boolean) => void;
  savedLoading: boolean;
  savedSearches: SavedSearch[];
  onApplySavedSearch: (s: SavedSearch) => void;
  onDeleteSavedSearch: (id: number) => void;
}

export function SearchFilterBar(props: SearchFilterBarProps) {
  const {
    query,
    setQuery,
    fromFilter,
    setFromFilter,
    toFilter,
    setToFilter,
    dateFrom,
    setDateFrom,
    dateTo,
    setDateTo,
    sort,
    setSort,
    hasAttachment,
    setHasAttachment,
    searching,
    onSubmit,
    onOpenUpload,
    hasActiveSearch,
    savePopoverOpen,
    setSavePopoverOpen,
    saveName,
    setSaveName,
    saving,
    onSaveSearch,
    savedListOpen,
    setSavedListOpen,
    savedLoading,
    savedSearches,
    onApplySavedSearch,
    onDeleteSavedSearch,
  } = props;

  return (
    <form onSubmit={onSubmit} className="space-y-4">
      <div className="flex flex-wrap items-center gap-2">
        <Input
          placeholder="Volltextsuche..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="w-full flex-1 sm:w-auto"
          aria-label="Suchbegriff"
        />
        <Button type="submit" disabled={searching} className="flex-1 sm:flex-none">
          {searching ? "Suche..." : "Suchen"}
        </Button>
        <Button type="button" variant="outline" onClick={onOpenUpload} className="flex-1 sm:flex-none">
          Importieren
        </Button>
        {hasActiveSearch && (
          <Popover open={savePopoverOpen} onOpenChange={setSavePopoverOpen}>
            <PopoverTrigger asChild>
              <Button type="button" variant="outline" size="icon" title="Suche speichern" aria-label="Suche speichern">
                <BookmarkPlus className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-72" align="end">
              <div className="space-y-3">
                <p className="text-sm font-medium">Suche speichern</p>
                <Input
                  placeholder="Name der Suche..."
                  value={saveName}
                  onChange={(e) => setSaveName(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") onSaveSearch(); }}
                  aria-label="Name der gespeicherten Suche"
                  autoFocus
                />
                <div className="flex justify-end gap-2">
                  <Button size="sm" variant="outline" onClick={() => setSavePopoverOpen(false)}>
                    Abbrechen
                  </Button>
                  <Button size="sm" onClick={onSaveSearch} disabled={saving || !saveName.trim()}>
                    {saving ? "Speichern..." : "Speichern"}
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>
        )}
        <Popover open={savedListOpen} onOpenChange={setSavedListOpen}>
          <PopoverTrigger asChild>
            <Button type="button" variant="outline" size="icon" title="Gespeicherte Suchen" aria-label="Gespeicherte Suchen">
              <Bookmark className="h-4 w-4" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-80" align="end">
            <p className="text-sm font-medium mb-3">Gespeicherte Suchen</p>
            {savedLoading ? (
              <div className="space-y-2">
                <Skeleton className="h-8 w-full" />
                <Skeleton className="h-8 w-full" />
              </div>
            ) : savedSearches.length === 0 ? (
              <p className="text-sm text-muted-foreground py-4 text-center">
                Keine gespeicherten Suchen vorhanden.
              </p>
            ) : (
              <div className="space-y-1 max-h-64 overflow-y-auto">
                {savedSearches.map((s) => (
                  <div
                    key={s.id}
                    className="flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted group"
                  >
                    <button
                      type="button"
                      className="flex-1 text-left text-sm truncate"
                      onClick={() => onApplySavedSearch(s)}
                      title={Object.entries(s.query).map(([k, v]) => `${k}: ${v}`).join(", ")}
                    >
                      {s.name}
                    </button>
                    <span className="text-xs text-muted-foreground whitespace-nowrap hidden group-hover:inline">
                      {new Date(s.created_at).toLocaleDateString("de-DE")}
                    </span>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                      onClick={(e) => { e.stopPropagation(); onDeleteSavedSearch(s.id); }}
                      aria-label={`Suche "${s.name}" loeschen`}
                    >
                      <Trash2 className="h-3.5 w-3.5 text-destructive" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </PopoverContent>
        </Popover>
      </div>

      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <div className="space-y-1">
          <Label htmlFor="from-filter" className="text-xs">
            Von (Absender)
          </Label>
          <Input
            id="from-filter"
            placeholder="absender@example.com"
            value={fromFilter}
            onChange={(e) => setFromFilter(e.target.value)}
            aria-label="Absender filtern"
          />
        </div>
        <div className="space-y-1">
          <Label htmlFor="to-filter" className="text-xs">
            An (Empfänger)
          </Label>
          <Input
            id="to-filter"
            placeholder="empfaenger@example.com"
            value={toFilter}
            onChange={(e) => setToFilter(e.target.value)}
            aria-label="Empfänger filtern"
          />
        </div>
        <div className="space-y-1">
          <Label htmlFor="date-from" className="text-xs">
            Datum von
          </Label>
          <Input
            id="date-from"
            type="date"
            value={dateFrom}
            onChange={(e) => setDateFrom(e.target.value)}
            aria-label="Datum von"
          />
        </div>
        <div className="space-y-1">
          <Label htmlFor="date-to" className="text-xs">
            Datum bis
          </Label>
          <Input
            id="date-to"
            type="date"
            value={dateTo}
            onChange={(e) => setDateTo(e.target.value)}
            aria-label="Datum bis"
          />
        </div>
      </div>

      <div className="flex flex-wrap items-center gap-4">
        <div className="flex items-center gap-2">
          <Label htmlFor="sort-select" className="text-xs whitespace-nowrap">Sortierung</Label>
          <Select value={sort} onValueChange={setSort}>
            <SelectTrigger id="sort-select" className="h-8 w-40 text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="date_desc">Datum (neu → alt)</SelectItem>
              <SelectItem value="date_asc">Datum (alt → neu)</SelectItem>
              <SelectItem value="relevance">Relevanz</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="flex items-center gap-2">
          <Switch
            id="attach-toggle"
            checked={hasAttachment === true}
            onCheckedChange={(checked) =>
              setHasAttachment(checked ? true : undefined)
            }
          />
          <Label htmlFor="attach-toggle" className="text-xs cursor-pointer">
            Nur mit Anhang
          </Label>
        </div>
      </div>
    </form>
  );
}
