"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 {
  saveMediaBlastAccount,
  saveMediaBlastCampaign,
} from "@/service/broadcast/broadcast";
import { error } from "@/config/swal";
import { useRouter } from "@/i18n/routing";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

const FormSchema = z.object({
  name: z.string({
    required_error: "Required",
  }),
  accountType: z
    .array(z.string())
    .refine((value) => value.some((item) => item), {
      message: "Required",
    }),
  accountCategory: z.enum(["polri", "jurnalis", "umumu", "ksp"], {
    required_error: "Required",
  }),
  email: z.string({
    required_error: "Required",
  }),
  whatsapp: z.string({
    required_error: "Required",
  }),
});

export default function CreateAccountForBroadcast() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: { accountType: [] },
  });

  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/account-list");
      }
    });
  }

  const save = async (data: z.infer<typeof FormSchema>) => {
    const reqData = {
      accountName: data.name,
      accountType: data.accountType.join(","),
      accountCategory: data.accountCategory,
      emailAddress: data.email,
      whatsappNumber: data.whatsapp,
    };
    console.log("data", data);

    const response = await saveMediaBlastAccount(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">Account</p>
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Nama</FormLabel>
                <Input
                  value={field.value}
                  placeholder="Masukkan nama"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="accountType"
            render={() => (
              <FormItem>
                <FormLabel>Tipe Akun</FormLabel>
                <div className="flex flex-row gap-2">
                  {" "}
                  <FormField
                    key="wa"
                    control={form.control}
                    name="accountType"
                    render={({ field }) => {
                      return (
                        <FormItem
                          key="wa"
                          className="flex flex-row items-start space-x-3 space-y-0"
                        >
                          <FormControl>
                            <Checkbox
                              checked={field.value?.includes("wa")}
                              onCheckedChange={(checked) => {
                                return checked
                                  ? field.onChange([...field.value, "wa"])
                                  : field.onChange(
                                      field.value?.filter(
                                        (value) => value !== "wa"
                                      )
                                    );
                              }}
                            />
                          </FormControl>
                          <FormLabel className="font-normal">
                            Whatsapp
                          </FormLabel>
                        </FormItem>
                      );
                    }}
                  />
                  <FormField
                    key="email"
                    control={form.control}
                    name="accountType"
                    render={({ field }) => {
                      return (
                        <FormItem
                          key="email"
                          className="flex flex-row items-start space-x-3 space-y-0"
                        >
                          <FormControl>
                            <Checkbox
                              checked={field.value?.includes("email")}
                              onCheckedChange={(checked) => {
                                return checked
                                  ? field.onChange([...field.value, "email"])
                                  : field.onChange(
                                      field.value?.filter(
                                        (value) => value !== "email"
                                      )
                                    );
                              }}
                            />
                          </FormControl>
                          <FormLabel className="font-normal">Email</FormLabel>
                        </FormItem>
                      );
                    }}
                  />
                </div>

                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="accountCategory"
            render={({ field }) => (
              <FormItem className="space-y-3">
                <FormLabel>Kategori</FormLabel>
                <FormControl>
                  <RadioGroup
                    onValueChange={field.onChange}
                    defaultValue={field.value}
                    className="flex flex-row gap-2"
                  >
                    <FormItem className="flex items-center space-x-3 space-y-0">
                      <FormControl>
                        <RadioGroupItem value="polri" />
                      </FormControl>
                      <FormLabel className="font-normal">POLRI</FormLabel>
                    </FormItem>
                    <FormItem className="flex items-center space-x-3 space-y-0">
                      <FormControl>
                        <RadioGroupItem value="jurnalis" />
                      </FormControl>
                      <FormLabel className="font-normal">JURNALIS</FormLabel>
                    </FormItem>
                    <FormItem className="flex items-center space-x-3 space-y-0">
                      <FormControl>
                        <RadioGroupItem value="umum" />
                      </FormControl>
                      <FormLabel className="font-normal">UMUM</FormLabel>
                    </FormItem>
                    <FormItem className="flex items-center space-x-3 space-y-0">
                      <FormControl>
                        <RadioGroupItem value="ksp" />
                      </FormControl>
                      <FormLabel className="font-normal">KSP</FormLabel>
                    </FormItem>
                  </RadioGroup>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Nama</FormLabel>
                <Input
                  type="email"
                  value={field.value}
                  placeholder="Masukkan email"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="whatsapp"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Nama</FormLabel>
                <Input
                  type="number"
                  value={field.value}
                  placeholder="Masukkan whatsapp"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <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>
  );
}
