import { useState } from "react";
import {
  CalendarDays,
  Filter,
  Layers3,
  RefreshCw,
  RotateCcw,
} from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";

export interface ReportFilterOption {
  id: string;
  label: string;
  parentId?: string | null;
  unitId?: string | null;
}

interface SectorReportFiltersProps {
  units: ReportFilterOption[];
  sectors: ReportFilterOption[];
  groups: ReportFilterOption[];
  unitId: string;
  sectorId: string;
  groupId: string;
  fromDate: string;
  toDate: string;
  loading?: boolean;
  refreshing?: boolean;
  onUnitChange: (value: string) => void;
  onSectorChange: (value: string) => void;
  onGroupChange: (value: string) => void;
  onFromDateChange: (value: string) => void;
  onToDateChange: (value: string) => void;
  onReset: () => void;
  onRefresh: () => void;
}

export function SectorReportFilters({
  units,
  sectors,
  groups,
  unitId,
  sectorId,
  groupId,
  fromDate,
  toDate,
  loading,
  refreshing,
  onUnitChange,
  onSectorChange,
  onGroupChange,
  onFromDateChange,
  onToDateChange,
  onReset,
  onRefresh,
}: SectorReportFiltersProps) {
  const [showAdvanced, setShowAdvanced] = useState(
    Boolean(groupId || fromDate || toDate),
  );
  const advancedFilterCount = [groupId, fromDate, toDate].filter(Boolean).length;

  return (
    <div className="w-full rounded-lg border bg-card p-4 shadow-sm lg:w-auto lg:min-w-[470px]">
      <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_40px_40px] items-end gap-3">
      <label className="space-y-1.5 text-xs font-medium">
        <span className="text-[9px] font-semibold uppercase tracking-[0.14em] text-muted-foreground">
          Filter by unit
        </span>
        <Select
          value={unitId}
          disabled={loading}
          onValueChange={onUnitChange}>
          <SelectTrigger className="h-9 w-full bg-background text-xs">
            <SelectValue placeholder="Select a unit" />
          </SelectTrigger>
          <SelectContent>
            {units.map((unit) => (
              <SelectItem key={unit.id} value={unit.id}>
                {unit.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </label>

      <label className="space-y-1.5 text-xs font-medium">
        <span className="text-[9px] font-semibold uppercase tracking-[0.14em] text-muted-foreground">
          Sector
        </span>
        <Select
          value={sectorId || "all"}
          disabled={!unitId || loading}
          onValueChange={(value) => onSectorChange(value === "all" ? "" : value)}>
          <SelectTrigger className="h-9 w-full bg-background text-xs">
            <SelectValue
              placeholder={unitId ? "All sectors" : "Select a unit first"}
            />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All sectors</SelectItem>
            {sectors.map((sector) => (
              <SelectItem key={sector.id} value={sector.id}>
                {sector.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </label>

      <Button
        type="button"
        size="icon"
        className="relative size-9 bg-emerald-800 text-white hover:bg-emerald-700"
        aria-label="Toggle advanced filters"
        aria-expanded={showAdvanced}
        onClick={() => setShowAdvanced((visible) => !visible)}>
        <Filter className="size-4" />
        {advancedFilterCount > 0 && (
          <span className="absolute -right-1.5 -top-1.5 flex size-4 items-center justify-center rounded-full bg-violet-600 text-[9px] font-bold text-white">
            {advancedFilterCount}
          </span>
        )}
      </Button>
      <Button
        type="button"
        variant="outline"
        size="icon"
        className="size-9"
        disabled={!unitId || refreshing}
        aria-label="Refresh sector report"
        onClick={onRefresh}>
        <RefreshCw className={`size-4 ${refreshing ? "animate-spin" : ""}`} />
      </Button>
      </div>

      {showAdvanced && (
      <div className="mt-4 grid gap-3 border-t pt-4 sm:grid-cols-2">
      <label className="space-y-1.5 text-xs font-medium sm:col-span-2">
        <span className="flex items-center gap-2">
          <Layers3 className="size-4 text-primary" />
          Group
        </span>
        <Select
          value={groupId || "all"}
          disabled={!unitId || !sectorId || loading}
          onValueChange={(value) => onGroupChange(value === "all" ? "" : value)}>
          <SelectTrigger className="h-9 w-full bg-background text-xs">
            <SelectValue
              placeholder={sectorId ? "All groups" : "Select a sector first"}
            />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All groups</SelectItem>
            {groups.map((group) => (
              <SelectItem key={group.id} value={group.id}>
                {group.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </label>

      <label className="space-y-1.5 text-xs font-medium">
        <span className="flex items-center gap-2">
          <CalendarDays className="size-4 text-primary" />
          From date
        </span>
        <input
          type="date"
          value={fromDate}
          max={toDate || undefined}
          disabled={!unitId || loading}
          onChange={(event) => onFromDateChange(event.target.value)}
          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
        />
      </label>

      <label className="space-y-1.5 text-xs font-medium">
        <span className="flex items-center gap-2">
          <CalendarDays className="size-4 text-primary" />
          To date
        </span>
        <input
          type="date"
          value={toDate}
          min={fromDate || undefined}
          disabled={!unitId || loading}
          onChange={(event) => onToDateChange(event.target.value)}
          className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
        />
      </label>

      <Button
        variant="outline"
        size="sm"
        className="gap-2 sm:col-span-2 sm:justify-self-end"
        disabled={!unitId}
        onClick={onReset}>
        <RotateCcw className="size-4" />
        Reset
      </Button>
      </div>
      )}
    </div>
  );
}
