"use client";

import postData from "@/api/post-data";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { format } from "date-fns";
import { CalendarIcon } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

export default function Statistics({}) {
  const t = useTranslations("vendor");
  const e = useTranslations("form-errors");
  const locale = useLocale();
  const [date, setDate] = useState(null);
  const [res, setRes] = useState(null);
  const [selectedOption, setSelectedOption] = useState("all");
  const [statistics, setStatistics] = useState(null);
  const l = useLocale();

  const months = [
    { name: "January", value: 1 },
    { name: "February", value: 2 },
    { name: "March", value: 3 },
    { name: "April", value: 4 },
    { name: "May", value: 5 },
    { name: "June", value: 6 },
    { name: "July", value: 7 },
    { name: "August", value: 8 },
    { name: "September", value: 9 },
    { name: "October", value: 10 },
    { name: "November", value: 11 },
    { name: "December", value: 12 },
  ];
  const currentYear = new Date().getFullYear();
  const years = Array.from({ length: 10 }, (_, i) =>
    (currentYear - i).toString()
  );

  const formSchema = z
    .object({
      type: z.string().min(1, e("required")),
      day: z.string().optional(),
      month: z.string().optional(),
      year: z.string().optional(),
    })
    .refine((data) => data.type !== "day" || (data.type === "day" && !!date), {
      path: ["day"],
      message: e("required"),
    })
    .refine((data) => data.type !== "month" || (data.month && data.year), {
      message: e("required"),
      path: ["month"],
    })
    .refine((data) => data.type !== "month" || (data.month && data.year), {
      message: e("required"),
      path: ["year"],
    })
    .refine((data) => data.type !== "year" || data.year, {
      path: ["year"],
      message: e("required"),
    });

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      type: "all",
      day: "",
      month: "",
      year: "",
    },
  });

  const {
    formState: { isSubmitting },
  } = form;

  async function onSubmit(values) {
    const formData = new FormData();
    if (values.type == "all") {
      formData.append("type", "all");
    } else if (values.type == "day") {
      if (date) {
        formData.append("type", "day");
        formData.append("day", format(date, "yyyy-MM-dd"));
      }
    } else if (values.type == "month") {
      formData.append("type", "month");
      formData.append("month", values.month || "");
      formData.append("month_year", values.year || "");
    } else if (values.type == "year") {
      formData.append("type", "year");
      formData.append("year", values.year || "");
    }

    const res = await postData({
      endPoint: "/user/orders/statistics",
      body: formData,
      locale,
    });
    if (res.status == "success") {
      setStatistics(res);
      toastSuccess(t("statisticsFetched"));
    } else {
      setRes(res);
    }
  }

  return (
    <section className="max-md:mx-4 mt-12 mb-20 rounded-lg py-4 grid grid-cols-2 gap-5 bg-redd-600  ">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-4 max-w-80"
        >
          {/* Main Select */}
          <FormField
            name="type"
            control={form.control}
            render={({ field }) => (
              <FormItem>
                <label className="block mb-1 text-sm font-medium">
                  {t("chooseType")}
                </label>
                <FormControl>
                  <Select
                    dir={l === "en" ? "ltr" : "rtl"}
                    onValueChange={(value) => {
                      field.onChange(value);
                      setSelectedOption(value);
                    }}
                    value={field.value}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("selectOption")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">{t("all")}</SelectItem>
                      <SelectItem value="day">{t("day")}</SelectItem>
                      <SelectItem value="month">{t("month")}</SelectItem>
                      <SelectItem value="year">{t("year")}</SelectItem>
                    </SelectContent>
                  </Select>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* Conditional Fields */}
          {selectedOption == "day" && (
            <FormField
              name="day"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <label>{t("day")}</label>
                  <FormControl>
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button variant={"outline"} className="w-full">
                          <CalendarIcon />
                          {date ? (
                            format(date, "PPP")
                          ) : (
                            <span>{t("pickDate")}</span>
                          )}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent>
                        <Calendar
                          mode="single"
                          selected={date}
                          onSelect={(selectedDate) => {
                            setDate(selectedDate);
                          }}
                        />
                      </PopoverContent>
                    </Popover>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          )}
          {/* {res?.data ? <div className="text-red-500">{res.data.type[0]}</div> : ""} */}
          {selectedOption == "month" && (
            <>
              <FormField
                name="month"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <label>{t("month")}</label>
                    <FormControl>
                      <Select
                        onValueChange={field.onChange}
                        value={field.value}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder={t("selectMonth")} />
                        </SelectTrigger>
                        <SelectContent>
                          {months.map((month) => (
                            <SelectItem
                              key={month.value}
                              value={month.value.toString()}
                            >
                              {month.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                name="year"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <label>{t("year")}</label>
                    <FormControl>
                      <Select
                        onValueChange={field.onChange}
                        value={field.value}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder={t("selectYear")} />
                        </SelectTrigger>
                        <SelectContent className="h-52">
                          {years.map((year) => (
                            <SelectItem key={year} value={year}>
                              {year}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </>
          )}
          {selectedOption == "year" && (
            <FormField
              name="year"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <label>{t("year")}</label>
                  <FormControl>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <SelectTrigger>
                        <SelectValue placeholder={t("selectYear")} />
                      </SelectTrigger>
                      <SelectContent className="h-52">
                        {years.map((year) => (
                          <SelectItem key={year} value={year}>
                            {year}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          )}

          {/* Submit Button */}
          <SubmitButton
            className="w-28"
            isIcon={false}
            text={t("save")}
            loading={isSubmitting}
          />
        </form>
      </Form>

      {/* Display Statistics */}
      {statistics && (
        <div className="mt-8 p-4 border rounded-md relative mx-4 w-full md:w-72 overflow-hidden bg-blue-gray-500 bg-clip-border text-white shadow-lg shadow-blue-gray-500/40 bg-gradient-to-r from-gray-500 to-gray-600 space-y-2 text-xl">
          <h3 className="text-lg font-bold mb-4">{t("statisticsTitle")}</h3>
          <p className="gap-2 flex">
            {t("totalSum")}:<span>{statistics.total_sum}</span>
          </p>
          <p className="gap-2 flex">
            {t("ordersNumbers")}:<span> {statistics.orders_numbers}</span>
          </p>
          <p className="gap-2 flex">
            {t("totalProfit")}:<span> {statistics.total_profit}</span>
          </p>
        </div>
      )}
    </section>
  );
}
