"use client";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import { CalendarIcon } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { getOnlyDate } from "@/utils/globals";
import {
  getMediaBlastCampaignById,
  saveMediaBlastCampaign,
} from "@/service/broadcast/broadcast";
import { error } from "@/config/swal";
import { useRouter } from "@/i18n/routing";
import { useParams } from "next/navigation";
import { useEffect } from "react";

const FormSchema = z.object({
  date: z.date({
    required_error: "Required",
  }),
  title: z.string({
    required_error: "Required",
  }),
  time: z.string({
    required_error: "Required",
  }),
  status: z.string({
    required_error: "Required",
  }),
});

export default function EditCampaign() {
  const id = useParams()?.id;
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
  });

  useEffect(() => {
    async function getInitData() {
      const response = await getMediaBlastCampaignById(String(id));
      const date = response?.data?.data?.sendTime.split(" ");
      const dateInput: Date = new Date(date[0]);

      const time = date[1].split(":");

      form.setValue("title", response?.data?.data?.title);
      form.setValue("status", response?.data?.data?.status);
      form.setValue("date", new Date(format(dateInput, "dd-MM-yyyy")));
      form.setValue("time", `${time[0]}:${time[1]}`);
    }

    if (id != undefined) {
      getInitData();
    }
  }, [id]);

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    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);
      }
    });
  };

  function successSubmit() {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push("/admin/broadcast/campaign-list");
      }
    });
  }

  const save = async (data: z.infer<typeof FormSchema>) => {
    const newDate = getOnlyDate(data.date).split("-");
    const dates = `${newDate[2]}-${newDate[1]}-${newDate[0]}`;
    const reqData = {
      id: String(id),
      title: data.title,
      sendTime: `${dates} ${data.time}:00`,
      status: data.status,
    };

    const response = await saveMediaBlastCampaign(reqData);
    if (response?.error) {
      error(response.message);
      return false;
    }

    successSubmit();
  };
  return (
    <div>
      <SiteBreadcrumb />
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-3 bg-white rounded-sm p-4"
        >
          <p className="fonnt-semibold">Campaign</p>
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Judul</FormLabel>
                <Input
                  value={field.value}
                  placeholder="Masukkan Judul"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <p className="text-sm">Jadwal Kirim</p>
          <div className="flex flex-row gap-2">
            <FormField
              control={form.control}
              name="date"
              render={({ field }) => (
                <FormItem>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant={"outline"}
                        size="md"
                        className={cn(
                          "w-[200px] justify-start text-left font-normal border-gray-200",
                          !field.value && "text-muted-foreground"
                        )}
                      >
                        <CalendarIcon className="mr-2 h-4 w-4" />
                        {field.value ? (
                          format(field.value, "dd-MM-yyyy")
                        ) : (
                          <span>Masukkan Bulan</span>
                        )}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0">
                      <Calendar
                        mode="single"
                        selected={field.value}
                        onSelect={field.onChange}
                        initialFocus
                      />
                    </PopoverContent>
                  </Popover>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="time"
              render={({ field }) => (
                <FormItem>
                  <Input
                    type="time"
                    className="max-w-[100px]"
                    value={field.value}
                    placeholder="Masukkan Judul Perencanaan"
                    onChange={field.onChange}
                  />

                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="flex flex-row gap-2 mt-4 pt-4">
            <Button
              size="md"
              type="button"
              variant="outline"
              color="destructive"
              className="text-xs"
            >
              Cancel
            </Button>
            <Button size="md" type="submit" color="primary" className="text-xs">
              Submit
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
