"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, { 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 { error } from "@/config/swal";
import { savePlanning } from "@/service/agenda-setting/agenda-setting";

const FormSchema = z.object({
  month: z.date({
    required_error: "Required",
  }),
  title: z.string({
    required_error: "Required",
  }),
  detail: z.string({
    required_error: "Required",
  }),
});
export default function CreateMonthly() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  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 = {
      planningTypeId: 2,
      title: data.title,
      time: "3",
      description: data.detail,
      username: "",
      date: `${new Date(data.month).getMonth() + 1}/${new Date(
        data.month
      ).getFullYear()}`,
      status: "Open",
    };
    console.log("req", reqData, data.month);
    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/medsos-mediahub");
      }
    });
  };

  const handleMonthSelect = (selectedDate: Date | undefined) => {
    if (!selectedDate) return;
    const newDate = new Date(
      selectedDate.getFullYear(),
      selectedDate.getMonth(),
      1
    );
    form.setValue("month", newDate);
  };
  return (
    <div>
      <SiteBreadcrumb />
      <div className="flex flex-col gap-4">
        <div className="flex flex-row justify-center gap-5 mt-10">
          <div className="bg-primary rounded-full px-5 py-2 text-white text-sm">
            Bulanan
          </div>
          <Link
            href="/curator/task-plan/medsos-mediahub/create-weekly"
            className="bg-slate-200 text-black rounded-full px-5 py-2 text-sm"
          >
            Mingguan
          </Link>
          <Link
            href="/curator/task-plan/medsos-mediahub/create-daily"
            className="bg-slate-200 text-black rounded-full px-5 py-2 text-sm"
          >
            Harian
          </Link>
        </div>
        <div className="flex flex-col bg-white gap-2 p-6">
          <p className="text-lg">Perencanaan MediaHub Bulanan</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}
                    />

                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="month"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel>Pilih Bulan</FormLabel>
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button
                          variant={"outline"}
                          className={cn(
                            "w-[280px] justify-start text-left font-normal",
                            !field.value && "text-muted-foreground"
                          )}
                        >
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {field.value ? (
                            format(field.value, "MMMM yyyy")
                          ) : (
                            <span>Masukkan Bulan</span>
                          )}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0">
                        <Calendar
                          mode="single"
                          selected={field.value}
                          onSelect={handleMonthSelect}
                          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}
                    />

                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="flex flex-row gap-2 justify-end mt-4 pt-4">
                <Button type="submit" variant="outline" color="destructive">
                  Cancel
                </Button>
                <Button type="submit" color="primary">
                  Submit
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </div>
  );
}
