"use client";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { CalendarIcon, Filter } from "lucide-react";
import React, { useState } from "react";
import { DateRange } from "react-day-picker";
import {
  format,
  isWithinInterval,
  parseISO,
  startOfDay,
  endOfDay,
} from "date-fns";
import PDFcomponent from "@/components/custom/pdfComponent";
import PDFTableComponent from "@/components/custom/pdfComponent";
import { useGetBranchQuery } from "@/redux/services/branchs.api";
import { useSession } from "next-auth/react";

type Branch = {
  name: string;
  image?: string;
  phone: string;
  email: string;
  address: string;
  productCount: string | number;
  passcode: string;
  status: string;
  code: string;
  _id?: string;
};

const Page = () => {
  const [statusFilter, setStatusFilter] = useState<
    "All" | "Branch1" | "Branch2" | "Branch3"
  >("All");
  const {
    data: branches,
    isLoading: isBranchesLoading,
    error: branchesError,
  } = useGetBranchQuery();

  const { data: session } = useSession();

  const additionalBranches: Branch[] = [
    {
      name: "All Branches",
      phone: "N/A",
      email: "all@example.com",
      address: "N/A",
      productCount: 0,
      passcode: "all-passcode",
      status: "active",
      code: "ALL",
      _id: "",
    },
  ];

  const combinedBranches: Branch[] = React.useMemo(() => {
    if (!branches) return additionalBranches;
    return [...additionalBranches, ...branches];
  }, [branches]);
  const [selectedBranch, setSelectedBranch] = useState<Branch>(
    additionalBranches[0]
  );
  //  const [selectedBranch, setSelectedBranch] = useState<string| Branch>(
  // const [selectedBranch, setSelectedBranch] = useState<string>(branch[0]);
  const [date, setDate] = React.useState<DateRange | undefined>({
    from: undefined,
    to: undefined,
  });

  return (
    <>
      <div className="flex gap-4">
        <Select
          onValueChange={(value) => {
            const selected = combinedBranches.find(
              (branch) => branch.name === value
            );
            setSelectedBranch(selected!);
          }}
          defaultValue={selectedBranch.name}
        >
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Select Branch" />
          </SelectTrigger>
          <SelectContent>
            {combinedBranches.map((branch) => (
              <SelectItem key={branch._id} value={branch.name}>
                {branch.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant={"outline"}
              className={`w-[300px] justify-start text-left font-normal ${
                !date && "text-muted-foreground"
              }`}
            >
              <CalendarIcon className="mr-2 h-4 w-4" />
              {date?.from ? (
                date.to ? (
                  <>
                    {format(date.from, "LLL dd, y")} -{" "}
                    {format(date.to, "LLL dd, y")}
                  </>
                ) : (
                  format(date.from, "LLL dd, y")
                )
              ) : (
                <span>Pick a date range</span>
              )}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-auto p-0" align="start">
            <Calendar
              initialFocus
              mode="range"
              defaultMonth={date?.from}
              selected={date}
              onSelect={setDate}
              numberOfMonths={2}
            />
          </PopoverContent>
        </Popover>
      </div>
      <div>
        {date?.from ? (
          <PDFTableComponent
            Branch={selectedBranch._id?.toString()}
            From={new Date(date?.from).toISOString().split("T")[0]}
            To={
              date?.to
                ? new Date(date?.to).toISOString().split("T")[0]
                : undefined
            }
          />
        ) : (
          <pre className="h-[60vh] flex justify-center items-center w-[80vw]">
            Please Select Filter
          </pre>
        )}
      </div>
    </>
  );
};

export default Page;
