"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 } 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 { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

const FormSchema = z.object({
  date: z.date({
    required_error: "Required",
  }),
  title: z.string({
    required_error: "Required",
  }),
  detail: z.string({
    required_error: "Required",
  }),
  output: z.array(z.string()).refine((value) => value.some((item) => item), {
    message: "Required",
  }),
  unit: z.array(z.string()).refine((value) => value.some((item) => item), {
    message: "Required",
  }),
  type: z.enum(["publication", "amplification", "contra"], {
    required_error: "Required",
  }),
});

const items = [
  {
    id: "video",
    label: "Audio Visual",
  },
  {
    id: "image",
    label: "Foto",
  },
  {
    id: "audio",
    label: "Audio",
  },
  {
    id: "text",
    label: "Text",
  },
];

const units = [
  {
    id: "mabes",
    label: "Mabes Polri",
  },
  {
    id: "polda",
    label: "Polda",
  },
  {
    id: "polres",
    label: "Polres",
  },
];
export default function CreateMonthly() {
  const MySwal = withReactContent(Swal);

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      unit: [],
      output: [],
      detail: "",
    },
  });
  const editor = useRef(null);

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

  const output = form.watch("output");

  const isAllChecked = items.every((item) => output?.includes(item.id));

  const unit = form.watch("unit");

  const isAllUnitChecked = units.every((item) => unit?.includes(item.id));

  const handleAllCheckedChange = (checked: boolean | string) => {
    if (checked) {
      form.setValue(
        "output",
        items.map((item) => item.id)
      );
    } else {
      form.setValue("output", []);
    }
  };

  const handleItemCheckedChange = (id: string, checked: boolean | string) => {
    form.setValue(
      "output",
      checked ? [...output, id] : output.filter((value) => value !== id)
    );
  };

  const handleAllUnitCheckedChange = (checked: boolean | string) => {
    if (checked) {
      form.setValue(
        "unit",
        units.map((item) => item.id)
      );
    } else {
      form.setValue("unit", []);
    }
  };

  const handleUnitCheckedChange = (id: string, checked: boolean | string) => {
    form.setValue(
      "unit",
      checked ? [...unit, id] : unit.filter((value) => value !== id)
    );
  };

  return (
    <div>
      <SiteBreadcrumb />
      <div className="flex flex-col gap-4">
        <div className="flex flex-row justify-center gap-5 mt-10">
          <Link
            href="/curator/task-plan/medsos-mediahub/create-monthly"
            className="bg-slate-200 text-black rounded-full px-5 py-2 text-sm"
          >
            Bulanan
          </Link>
          <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>

          <div className="bg-primary rounded-full px-5 py-2 text-white text-sm">
            Harian
          </div>
        </div>
        <div className="flex flex-col bg-white gap-2 p-6">
          <p className="text-lg">Perencanaan MediaHub</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="output"
                render={() => (
                  <FormItem>
                    <div className="mb-4">
                      <FormLabel className="text-sm">Output Tugas</FormLabel>
                    </div>
                    <div className="flex flex-row gap-3 items-center ">
                      <div className="flex items-center gap-3">
                        <Checkbox
                          id="all"
                          checked={isAllChecked}
                          // indeterminate={isSomeChecked && !isAllChecked}
                          onCheckedChange={(checked) =>
                            handleAllCheckedChange(checked)
                          }
                        />
                        <label htmlFor="all" className="text-sm">
                          Semua
                        </label>
                      </div>

                      {items.map((item) => (
                        <FormField
                          key={item.id}
                          control={form.control}
                          name="output"
                          render={({ field }) => {
                            return (
                              <FormItem
                                key={item.id}
                                className="flex flex-row items-start space-x-3 space-y-0"
                              >
                                <FormControl>
                                  <Checkbox
                                    checked={output?.includes(item.id)}
                                    onCheckedChange={(checked) =>
                                      handleItemCheckedChange(item.id, checked)
                                    }
                                  />
                                </FormControl>
                                <FormLabel className="font-normal">
                                  {item.label}
                                </FormLabel>
                              </FormItem>
                            );
                          }}
                        />
                      ))}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="unit"
                render={() => (
                  <FormItem>
                    <div className="mb-4">
                      <FormLabel className="text-sm">Pelaksana Tugas</FormLabel>
                    </div>
                    <div className="flex flex-row gap-3 items-center ">
                      <div className="flex items-center gap-3">
                        <Checkbox
                          id="all"
                          checked={isAllUnitChecked}
                          onCheckedChange={(checked) =>
                            handleAllUnitCheckedChange(checked)
                          }
                        />
                        <label htmlFor="all" className="text-sm">
                          Semua
                        </label>
                      </div>

                      {units.map((item) => (
                        <FormField
                          key={item.id}
                          control={form.control}
                          name="unit"
                          render={({ field }) => {
                            return (
                              <FormItem
                                key={item.id}
                                className="flex flex-row items-start space-x-3 space-y-0"
                              >
                                <FormControl>
                                  <Checkbox
                                    checked={unit?.includes(item.id)}
                                    disabled={
                                      item.id === "polres" &&
                                      !unit.includes("polda")
                                    }
                                    onCheckedChange={(checked) =>
                                      handleUnitCheckedChange(item.id, checked)
                                    }
                                  />
                                </FormControl>
                                <FormLabel className="font-normal">
                                  {item.label}
                                </FormLabel>
                              </FormItem>
                            );
                          }}
                        />
                      ))}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Jenis Penugasan</FormLabel>
                    <FormControl>
                      <RadioGroup
                        onValueChange={field.onChange}
                        defaultValue={field.value}
                        className="flex flex-row gap-3"
                      >
                        <FormItem className="flex items-center space-x-3 space-y-0">
                          <FormControl>
                            <RadioGroupItem value="publication" />
                          </FormControl>
                          <FormLabel className="font-normal">
                            Publikasi
                          </FormLabel>
                        </FormItem>
                        <FormItem className="flex items-center space-x-3 space-y-0">
                          <FormControl>
                            <RadioGroupItem value="amplification" />
                          </FormControl>
                          <FormLabel className="font-normal">
                            Amplifikasi
                          </FormLabel>
                        </FormItem>
                        <FormItem className="flex items-center space-x-3 space-y-0">
                          <FormControl>
                            <RadioGroupItem value="contra" />
                          </FormControl>
                          <FormLabel className="font-normal">Kontra</FormLabel>
                        </FormItem>
                      </RadioGroup>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="date"
                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"
                          )}
                        >
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {field.value ? (
                            format(field.value, "PPP")
                          ) : (
                            <span>Masukkan Tanggal</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="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>
  );
}
