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';

import keyCarImg from '@/assets/images/car-keys.png';

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">
          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 o período" />
            </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>

          <Select>
            <SelectTrigger>
              <SelectValue placeholder="Selecione o veículo" />
            </SelectTrigger>

            <SelectContent className="rounded-md">
              <SelectItem value="all">
                <div className="flex items-center gap-2">
                  <span>Todos os veículos</span>
                </div>
              </SelectItem>

              <SelectItem value="fiat-uno-abc-1234">
                <div className="flex items-center gap-2">
                  <img src={keyCarImg} alt="Chave" className="w-5 h-5" />
                  <p>
                    <span className="font-bold">ABC1234</span> — Fiat Uno
                  </p>
                </div>
              </SelectItem>

              <SelectItem value="vw-gol-def-5678">
                <div className="flex items-center gap-2">
                  <img src={keyCarImg} alt="Chave" className="w-5 h-5" />
                  <p>
                    <span className="font-bold">DEF5678</span> — VW Gol
                  </p>
                </div>
              </SelectItem>

              <SelectItem value="hyundai-hb20-ghi-9012">
                <div className="flex items-center gap-2">
                  <img src={keyCarImg} alt="Chave" className="w-5 h-5" />
                  <p>
                    <span className="font-bold">GHI9012</span> — Hyundai HB20
                  </p>
                </div>
              </SelectItem>

              <SelectItem value="ford-ka-jkl-3456">
                <div className="flex items-center gap-2">
                  <img src={keyCarImg} alt="Chave" className="w-5 h-5" />
                  <p>
                    <span className="font-bold">JKL3456</span> — Ford Ka
                  </p>
                </div>
              </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>
  );
}
