"use client";

import { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { format, getYear, getMonth, addMonths, subMonths } from "date-fns";
import { useToast } from "@/hooks/use-toast";

export default function MonthYearPicker({ initialDate, basePath = '/admin/dashboard' }: { initialDate: Date, basePath?: string }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [date, setDate] = useState<Date>(initialDate);
  const [isOpen, setIsOpen] = useState(false);
  const { toast } = useToast();

  const years = Array.from({ length: 10 }, (_, i) => getYear(new Date()) - 5 + i);

  useEffect(() => {
    const month = searchParams.get('month');
    const year = searchParams.get('year');
    // Only show toast if the URL parameters have actually changed the date
    // and it's not the initial load.
    if (month && year) {
        const newDateFromParams = new Date(parseInt(year), parseInt(month) - 1);
        // This check prevents the toast from showing on initial page load
        if (newDateFromParams.getTime() !== initialDate.getTime()) {
             toast({
                title: "Data Updated",
                description: `Showing data for ${format(newDateFromParams, "MMMM yyyy")}`,
             });
             setDate(newDateFromParams);
        }
    }
  }, [searchParams, initialDate, toast]);


  const handleMonthChange = (direction: "next" | "prev") => {
    const newDate = direction === "next" ? addMonths(date, 1) : subMonths(date, 1);
    updateRoute(newDate);
  };

  const handleYearChange = (year: string) => {
    const newDate = new Date(date.setFullYear(parseInt(year)));
    updateRoute(newDate);
  };
  
  const handleMonthSelect = (month: number) => {
    const newDate = new Date(date.setMonth(month));
    updateRoute(newDate);
  }

  const updateRoute = (newDate: Date) => {
    const year = getYear(newDate);
    const month = getMonth(newDate) + 1;
    router.push(`${basePath}?year=${year}&month=${month}`);
  };

  return (
    <div className="flex items-center gap-2">
      <Button variant="outline" size="icon" onClick={() => handleMonthChange("prev")}>
        <ChevronLeft className="h-4 w-4" />
      </Button>
      <Popover open={isOpen} onOpenChange={setIsOpen}>
        <PopoverTrigger asChild>
          <Button variant="outline" className="w-[180px] justify-start text-left font-normal">
            {format(date, "MMMM yyyy")}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="flex w-auto flex-col space-y-2 p-2">
          <div className="flex justify-between items-center">
             <Select
                onValueChange={(value) => handleYearChange(value)}
                defaultValue={String(getYear(date))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select year" />
                </SelectTrigger>
                <SelectContent position="popper">
                  {years.map((year) => (
                    <SelectItem key={year} value={String(year)}>
                      {year}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
          </div>
          <div className="grid grid-cols-3 gap-2">
            {Array.from({ length: 12 }).map((_, i) => (
                <Button
                    key={i}
                    variant={getMonth(date) === i ? "default" : "outline"}
                    onClick={() => {
                        handleMonthSelect(i);
                        setIsOpen(false);
                    }}
                >
                   {format(new Date(getYear(date), i), 'MMM')}
                </Button>
            ))}
          </div>
        </PopoverContent>
      </Popover>
      <Button variant="outline" size="icon" onClick={() => handleMonthChange("next")}>
        <ChevronRight className="h-4 w-4" />
      </Button>
    </div>
  );
}
