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 { Funnel, 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';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@/views/components/ui/sheet';
import { SelectPopover } from './ui/select-popover';

type DateRange = RDateRange;

const projects = [
  { id: 1, descricao: 'Projeto Alfa' },
  { id: 2, descricao: 'Projeto Beta' },
  { id: 3, descricao: 'Projeto Gama' },
];

const sectors = [
  { id: 1, descricao: 'Manutenção' },
  { id: 2, descricao: 'Operações' },
  { id: 3, descricao: 'Logística' },
];

const clients = [
  { id: 1, descricao: 'Cliente A' },
  { id: 2, descricao: 'Cliente B' },
  { id: 3, descricao: 'Cliente C' },
];

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(),
  }));

  const [projectValue, setProjectValue] = useState<string>(
    projects[0]?.descricao ?? ''
  );
  const [sectorValue, setSectorValue] = useState<string>(
    sectors[0]?.descricao ?? ''
  );
  const [clientValue, setClientValue] = useState<string>(
    clients[0]?.descricao ?? ''
  );

  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">
          Gestão de Frota
        </h1>
        <p className="text-gray-500 dark:text-gray-400">
          Dashboard de visualização e controle da frota de veículos
        </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>
              <SelectValue placeholder="Selecione um opção" />
            </SelectTrigger>

            <SelectContent className="rounded-md">
              <SelectItem value="0">Ultimo dia</SelectItem>
              <SelectItem value="7">Últimos 7 dias</SelectItem>
              <SelectItem value="30">Últimos 30 dias</SelectItem>
              <SelectItem value="90">Últimos 90 dias</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>

        <Sheet>
          <SheetTrigger asChild>
            <Button
              title="Clique para visualizar os filtros"
              variant="outline"
              size="icon"
            >
              <Funnel size={18} />
            </Button>
          </SheetTrigger>
          <SheetContent className="w-fit space-y-4">
            <SheetHeader>
              <SheetTitle className="mt-1.5">Filtros</SheetTitle>
            </SheetHeader>

            <div className="flex flex-col gap-3 w-[204px]">
              <SelectPopover
                label="Projeto"
                items={projects || []}
                value={projectValue}
                setValue={setProjectValue}
                placeholder="Selecione um projeto..."
              />

              <SelectPopover
                label="Setor"
                items={sectors || []}
                value={sectorValue}
                setValue={setSectorValue}
                placeholder="Selecione um setor..."
              />

              <SelectPopover
                label="Cliente"
                items={clients || []}
                value={clientValue}
                setValue={setClientValue}
                placeholder="Selecione um cliente..."
              />
            </div>
          </SheetContent>
        </Sheet>
      </div>
    </header>
  );
}
