"use client";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Link, useRouter } from "@/i18n/routing";
import { CalendarIcon } from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import JoditEditor from "jodit-react";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, error, loading } from "@/config/swal";
import { getOnlyDate } from "@/utils/globals";
import {
  getMonthlyPlanList,
  savePlanning,
} from "@/service/agenda-setting/agenda-setting";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import dayjs from "dayjs";
import { getPlanningById } from "@/service/planning/planning";
import { useParams } from "next/navigation";

const FormSchema = z.object({
  week: z.object({
    from: z.date({
      required_error: "Start date (from) is required",
    }),
    to: z.date({
      required_error: "End date (to) is required",
    }),
  }),
  title: z.string({
    required_error: "Required",
  }),
  detail: z.string({
    required_error: "Required",
  }),
});
export default function DetailMonthly() {
  const id = useParams()?.id;
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const [parentId, setParentId] = useState<number | undefined>();
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      detail: "",
    },
  });

  const editor = useRef(null);

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    if (form.getValues("detail") == "") {
      form.setError("detail", {
        type: "manual",
        message: "Required",
      });
    } else {
      MySwal.fire({
        title: "Simpan Data",
        text: "Apakah Anda yakin ingin menyimpan data ini?",
        icon: "warning",
        showCancelButton: true,
        cancelButtonColor: "#d33",
        confirmButtonColor: "#3085d6",
        confirmButtonText: "Simpan",
      }).then((result) => {
        if (result.isConfirmed) {
          save(data);
        }
      });
    }
  };

  const save = async (data: z.infer<typeof FormSchema>) => {
    const reqData = {
      id: id,
      planningTypeId: 1,
      title: data.title,
      time: "2",
      description: data.detail,
      username: "",
      date: `${getOnlyDate(data.week.from)} - ${getOnlyDate(data.week.to)}`,
      status: "Open",
      parentId: parentId,
    };
    console.log("req", reqData);
    const response = await savePlanning(reqData);
    close();
    if (response?.error) {
      error(response?.message);
      return false;
    }

    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push("/curator/task-plan/mediahub");
      }
    });
  };

  useEffect(() => {
    async function getPlanningData() {
      if (id != undefined) {
        loading();
        const res = await getPlanningById(id);
        close();
        if (res?.data?.data != undefined) {
          const data = res?.data?.data;
          console.log("Data :", data);
          form.setValue("title", data?.title);
          form.setValue("week", {
            from: new Date(data?.startDate),
            to: new Date(data?.endDate),
          });
          form.setValue("detail", data.description);
          setParentId(data?.parentId);
        }
      }
    }

    getPlanningData();
  }, []);

  return (
    <div>
      <SiteBreadcrumb />
      <div className="flex flex-col gap-4">
        <div className="flex flex-col bg-white gap-2 p-6">
          <p className="text-lg">Perencanaan MediaHub Mingguan</p>

          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Judul Perencanaan</FormLabel>
                    <Input
                      value={field.value}
                      placeholder="Masukkan Judul Perencanaan"
                      onChange={field.onChange}
                      readOnly
                    />

                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="week"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel>Pilih Tanggal</FormLabel>
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button
                          variant={"outline"}
                          className={cn(
                            "w-[280px] justify-start text-left font-normal",
                            !field.value && "text-muted-foreground"
                          )}
                          disabled
                        >
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {field.value?.from ? (
                            field.value.to ? (
                              <>
                                {format(field.value.from, "LLL dd, y")} -{" "}
                                {format(field.value.to, "LLL dd, y")}
                              </>
                            ) : (
                              format(field.value.from, "LLL dd, y")
                            )
                          ) : (
                            <span>Masukkan Tanggal</span>
                          )}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0">
                        <Calendar
                          mode="range"
                          selected={field.value}
                          onSelect={field.onChange}
                          initialFocus
                        />
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="detail"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Detail Perencanaan</FormLabel>
                    <JoditEditor
                      ref={editor}
                      value={field.value}
                      className="dark:text-black"
                      onChange={field.onChange}
                      config={{ readonly: true }}
                    />

                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="flex flex-row gap-2 justify-end mt-4 pt-4">
                <Button
                  onClick={() => router.back()}
                  variant="outline"
                  color="destructive"
                  type="button"
                >
                  Back
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </div>
  );
}
