import { distributed_api } from "@/features/distributed/lib/api";
import { order_api } from "@/features/specification/lib/api";
import formatDate from "@/shared/lib/formatDate";
import { Button } from "@/shared/ui/button";
import { Calendar } from "@/shared/ui/calendar";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/shared/ui/command";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ChevronDownIcon, ChevronsUpDown } from "lucide-react";
import { useState } from "react";

interface Props {
  open: boolean;
  setOpen: (v: boolean) => void;
}

export default function DistributedAddModal({ open, setOpen }: Props) {
  const [form, setForm] = useState({
    product_id: 0,
    date: "",
    employee_name: "",
    quantity: 0,
  });

  const client = useQueryClient();

  const { data: product } = useQuery({
    queryKey: ["product_list"],
    queryFn: () => order_api.product_list(),
    select(data) {
      return data.data.data;
    },
  });

  const [openProduct, setOpenProduct] = useState(false);
  const [searchProduct, setSearchProduct] = useState("");
  const [openDate, setOpenData] = useState(false);

  const selectedProduct = product?.find((x) => x.id === form.product_id);

  const createMutation = useMutation({
    mutationFn: () => distributed_api.create(form),
    onSuccess: () => {
      client.invalidateQueries({ queryKey: ["distributed_list"] });
      setOpen(false);
    },
  });

  const handleSubmit = () => {
    createMutation.mutate();
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="space-y-4 max-w-md">
        <DialogHeader>
          <DialogTitle>Yangi topshirilgan mahsulot qo‘shish</DialogTitle>
        </DialogHeader>

        <div className="flex flex-col gap-3 space-y-3">
          <div className="flex flex-col gap-3">
            <Label>Topshirilga mahsulot</Label>
            <Popover open={openProduct} onOpenChange={setOpenProduct}>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="outline"
                  role="combobox"
                  aria-expanded={openProduct}
                  className="w-full h-11 justify-between"
                >
                  {selectedProduct ? selectedProduct.name : "Mahsulot tanlang"}
                  <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" />
                </Button>
              </PopoverTrigger>

              <PopoverContent
                className="w-[--radix-popover-trigger-width] p-0"
                align="start"
              >
                <Command shouldFilter={false}>
                  <CommandInput
                    placeholder="Qidirish..."
                    className="h-9"
                    value={searchProduct}
                    onValueChange={setSearchProduct}
                  />

                  <CommandList>
                    {product && product.length > 0 ? (
                      <CommandGroup>
                        {product
                          .filter((p) =>
                            p.name
                              .toLowerCase()
                              .includes(searchProduct.toLowerCase()),
                          )
                          .map((p) => (
                            <CommandItem
                              key={p.id}
                              value={`${p.id}`}
                              onSelect={() => {
                                setForm({ ...form, product_id: p.id });
                                setOpenProduct(false);
                              }}
                            >
                              {p.name}
                            </CommandItem>
                          ))}
                      </CommandGroup>
                    ) : (
                      <CommandEmpty>Mahsulot topilmadi</CommandEmpty>
                    )}
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>

          <div className="flex flex-col gap-3">
            <Label>Mahsulot soni</Label>
            <Input
              type="text"
              placeholder="Miqdori"
              value={form.quantity}
              onChange={(e) => {
                const val = e.target.value;
                setForm({ ...form, quantity: val === "" ? 0 : Number(val) });
              }}
            />
          </div>

          <div className="flex flex-col gap-3">
            <Label>Xaridorning ismi</Label>
            <Input
              placeholder="Xodim ismi"
              value={form.employee_name}
              onChange={(e) =>
                setForm({ ...form, employee_name: e.target.value })
              }
            />
          </div>

          <div className="flex flex-col gap-3">
            <Label htmlFor="date" className="px-1">
              Topshirilgan sana
            </Label>

            <Popover open={openDate} onOpenChange={setOpenData}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  id="date"
                  className="w-full h-12 justify-between font-normal"
                >
                  {form.date ? form.date : "Sanani kiriting"}
                  <ChevronDownIcon />
                </Button>
              </PopoverTrigger>
              <PopoverContent
                className="w-auto overflow-hidden p-0"
                align="start"
              >
                <Calendar
                  mode="single"
                  selected={new Date(form.date)}
                  captionLayout="dropdown"
                  onSelect={(date) => {
                    if (date) {
                      setForm({
                        ...form,
                        date: formatDate.format(date, "YYYY-MM-DD"),
                      });
                      setOpenData(false);
                    }
                  }}
                />
              </PopoverContent>
            </Popover>
          </div>
        </div>

        <Button
          onClick={handleSubmit}
          disabled={createMutation.isPending}
          className="h-12"
        >
          {createMutation.isPending ? "Saqlanmoqda..." : "Saqlash"}
        </Button>
      </DialogContent>
    </Dialog>
  );
}
