import { Button } from '@/views/components/ui/button';
import { Calendar } from '@/views/components/ui/calendar';
import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from '@/views/components/ui/drawer';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/views/components/ui/popover';
import { GearSix } from '@phosphor-icons/react';
import { ptBR } from 'date-fns/locale';
import { useState } from 'react';

import type { DateRange as RDateRange } from 'react-day-picker';

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/views/components/ui/select';

type DateRange = RDateRange;

export function Header() {
  const [isPopoverOpen, setIsPopoverOpen] = useState(false);
  const [localDateRange, setLocalDateRange] = useState<DateRange | undefined>();

  const [dateValue, setDateValue] = useState<DateRange | undefined>(() => ({
    from: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7),
    to: new Date(),
  }));

  function handlePopoverOpenChange(open: boolean) {
    setIsPopoverOpen(open);
    if (open) {
      setLocalDateRange(dateValue);
    }
  }

  function clearDateFilter() {
    setDateValue(undefined);
    setLocalDateRange(undefined);
    setIsPopoverOpen(false);
  }

  function applyDateFilter() {
    setDateValue(localDateRange);
    setIsPopoverOpen(false);
  }

  function formatDateRange() {
    if (!dateValue?.from) return 'Período';
    const from = dateValue.from.toLocaleDateString('pt-BR');
    if (!dateValue?.to) return `A partir de ${from}`;
    const to = dateValue.to.toLocaleDateString('pt-BR');
    return `${from} — ${to}`;
  }

  return (
    <header className="animate-slidein300 opacity-0 flex mb-6 md:block lg:flex items-center justify-between z-50">
      <div className="md:mb-2">
        <h1 className="mt-2 text-2xl font-medium tracking-tight text-slate-900 dark:text-slate-100">
          Tramitação de Protocolo
        </h1>
        <p className="text-gray-500 dark:text-gray-400">
          Monitoramento e gestão eficiente de protocolos
        </p>
      </div>

      <div className="md:hidden">
        <Drawer>
          <DrawerTrigger asChild>
            <Button variant="outline" size="icon">
              <GearSix size={18} />
            </Button>
          </DrawerTrigger>
          <DrawerContent>
            <div className="mx-auto w-full max-w-sm">
              <DrawerHeader>
                <DrawerTitle>Filtros e Configurações</DrawerTitle>
                <DrawerDescription>
                  Personalize o que deseja visualizar.
                </DrawerDescription>
              </DrawerHeader>

              <DrawerFooter className="flex-row gap-2">
                <Button className="flex-1" onClick={() => window.print()}>
                  Gerar Relatório
                </Button>
              </DrawerFooter>
            </div>
          </DrawerContent>
        </Drawer>
      </div>

      <div className="hidden md:flex items-center gap-2">
        <div className="flex items-center gap-2">
          <Button onClick={() => window.print()}>Gerar Relatório</Button>

          <Select>
            <SelectTrigger className="w-[180px]" value="0">
              <SelectValue placeholder="Selecione um opção" />
            </SelectTrigger>

            <SelectContent className="rounded-md">
              <SelectItem value="0">Modo Eu</SelectItem>
              <SelectItem value="7">Todos os protocolos</SelectItem>
            </SelectContent>
          </Select>

          <Popover open={isPopoverOpen} onOpenChange={handlePopoverOpenChange}>
            <PopoverTrigger asChild>
              <Button className="w-full sm:w-fit" variant="outline">
                {formatDateRange()}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0 bg-white" align="start">
              <div className="p-2">
                <Calendar
                  mode="range"
                  selected={localDateRange}
                  onSelect={setLocalDateRange}
                  className="capitalize"
                  locale={ptBR}
                  initialFocus
                  numberOfMonths={2}
                />
                <div className="flex justify-between p-2">
                  <Button
                    variant="ghost"
                    onClick={clearDateFilter}
                    disabled={!dateValue?.from}>
                    Limpar
                  </Button>
                  <Button
                    onClick={applyDateFilter}
                    disabled={!localDateRange?.from}>
                    Aplicar
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>
        </div>
      </div>
    </header>
  );
}
