// components/TambahIklanModal.tsx
"use client";

import * as React from "react";
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { CalendarIcon, ChevronDown, ChevronUp, Plus } from "lucide-react";
import { useTranslations } from "next-intl";
import DatePicker from "react-datepicker";
import { id } from "date-fns/locale";
import "react-datepicker/dist/react-datepicker.css";
import { zodResolver } from "@hookform/resolvers/zod";
import router from "next/router";
import { Controller, useForm } from "react-hook-form";
import { date, z } from "zod";
import { error } from "@/lib/swal";
import { postCalendar } from "@/service/schedule/schedule";
import { DateRange } from "react-day-picker";
import Cookies from "js-cookie";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import { Label } from "@/components/ui/label";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { getUserLevelForAssignments } from "@/service/task";
import { Card } from "@/components/ui/card";

const calendarSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  description: z.string().min(1, { message: "Judul diperlukan" }),
});

export function CalendarPolriAdd() {
  const MySwal = withReactContent(Swal);
  const [open, setOpen] = React.useState(false);
  const t = useTranslations("Schedule");
  type CalendarSchema = z.infer<typeof calendarSchema>;
  const [eventDate, setEventDate] = React.useState<Date | null>(new Date());
  const [listDest, setListDest] = React.useState([]);
  const [checkedLevels, setCheckedLevels] = React.useState(new Set());
  const [expandedPolda, setExpandedPolda] = React.useState([{}]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [date, setDate] = React.useState<DateRange | undefined>({
    from: new Date(2025, 0, 1),
  });

  const [unitSelection, setUnitSelection] = React.useState({
    semua: false,
    mabes: false,
    polda: false,
    satker: false,
    internasional: false,
  });

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<CalendarSchema>({
    resolver: zodResolver(calendarSchema),
    defaultValues: {
      description: "",
    },
  });

  React.useEffect(() => {
    async function fetchPoldaPolres() {
      setIsLoading(true);
      try {
        const response = await getUserLevelForAssignments();
        setListDest(response?.data?.data.list);
        console.log("polda", response?.data?.data?.list);
        const initialExpandedState = response?.data?.data.list.reduce(
          (acc: any, polda: any) => {
            acc[polda.id] = false;
            return acc;
          },
          {}
        );
        setExpandedPolda(initialExpandedState);
        console.log("polres", initialExpandedState);
      } catch (error) {
        console.error("Error fetching Polda/Polres data:", error);
      } finally {
        setIsLoading(false);
      }
    }
    fetchPoldaPolres();
  }, []);

  const handleCheckboxChange = (levelId: number) => {
    setCheckedLevels((prev) => {
      const updatedLevels = new Set(prev);
      if (updatedLevels.has(levelId)) {
        updatedLevels.delete(levelId);
      } else {
        updatedLevels.add(levelId);
      }
      return updatedLevels;
    });
  };

  const handlePoldaPolresChange = () => {
    return Array.from(checkedLevels).join(","); // Mengonversi Set ke string
  };

  const handleUnitChange = (
    key: keyof typeof unitSelection,
    value: boolean
  ) => {
    if (key === "semua") {
      const newState = {
        semua: value,
        mabes: value,
        polda: value,
        satker: value,
        internasional: value,
      };
      setUnitSelection(newState);
    } else {
      const updatedSelection = {
        ...unitSelection,
        [key]: value,
      };

      const allChecked = ["mabes", "polda", "satker", "internasional"].every(
        (k) => updatedSelection[k as keyof typeof unitSelection]
      );

      updatedSelection.semua = allChecked;

      setUnitSelection(updatedSelection);
    }
  };

  const toggleExpand = (poldaId: any) => {
    setExpandedPolda((prev: any) => ({
      ...prev,
      [poldaId]: !prev[poldaId],
    }));
  };

  const save = async (data: CalendarSchema) => {
    const unitMapping = {
      allUnit: "0",
      mabes: "1",
      polda: "2",
      satker: "4",
      internasional: "5",
    };
    const assignmentToString = Object.keys(unitSelection)
      .filter((key) => unitSelection[key as keyof typeof unitSelection])
      .map((key) => unitMapping[key as keyof typeof unitMapping])
      .join(",");
    const requestData = {
      title: data.title,
      startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
      endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
      description: data.description,
      assignedTo: assignmentToString,
      assignedToLevel: handlePoldaPolresChange(),
    };

    console.log("Form Data Submitted:", requestData);

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

    Cookies.set("scheduleId", response?.data?.data.id, {
      expires: 1,
    });

    MySwal.fire({
      title: "Sukses",
      text: "Data berhasil disimpan.",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then(() => {
      router.reload();
    });
  };

  const onSubmit = (data: CalendarSchema) => {
    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);
      }
    });
  };

  return (
    <div>
      <Card className="px-3 py-3">
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="space-y-4">
            <div>
              <p className="font-medium mb-1">Tanggal Acara</p>
              <div className="flex flex-col space-y-2">
                <Popover>
                  <PopoverTrigger asChild className="px-0">
                    <Button
                      size="md"
                      id="date"
                      variant={"outline"}
                      className={cn(
                        "w-[280px] lg:w-[250px] justify-start text-left font-normal border border-slate-300 px-0 md:px-0 lg:px-4",
                        !date && "text-muted-foreground"
                      )}
                    >
                      <CalendarIcon size={15} className="mr-3" />
                      {date?.from ? (
                        date.to ? (
                          <>
                            {format(date.from, "LLL dd, y")} -{" "}
                            {format(date.to, "LLL dd, y")}
                          </>
                        ) : (
                          format(date.from, "LLL dd, y")
                        )
                      ) : (
                        <span>Pick a date</span>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      initialFocus
                      mode="range"
                      defaultMonth={date?.from}
                      selected={date}
                      onSelect={setDate}
                      numberOfMonths={1}
                    />
                  </PopoverContent>
                </Popover>
              </div>
            </div>
            <div>
              <p className="font-medium">Publish Area</p>
              <div className="flex flex-row">
                <div className="flex flex-wrap gap-3 lg:ml-3 ">
                  {Object.keys(unitSelection).map((key) => (
                    <div className="flex items-center gap-2" key={key}>
                      <Checkbox
                        id={key}
                        checked={
                          unitSelection[key as keyof typeof unitSelection]
                        }
                        onCheckedChange={(value) =>
                          handleUnitChange(
                            key as keyof typeof unitSelection,
                            value as boolean
                          )
                        }
                      />
                      <Label htmlFor={key}>
                        {key.charAt(0).toUpperCase() + key.slice(1)}
                      </Label>
                    </div>
                  ))}
                </div>
                <div className=" lg:pl-3">
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button variant="soft" size="sm" color="primary">
                        [{t("custom")}]
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-[425px] md:max-w-[500px] lg:max-w-[1500px]">
                      <DialogHeader>
                        <DialogTitle>
                          Daftar Wilayah Polda dan Polres
                        </DialogTitle>
                      </DialogHeader>
                      <div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto">
                        {listDest.map((polda: any) => (
                          <div key={polda.id} className="border p-2">
                            <Label className="flex items-center">
                              <Checkbox
                                checked={checkedLevels.has(polda.id)}
                                onCheckedChange={() =>
                                  handleCheckboxChange(polda.id)
                                }
                                className="mr-3"
                              />
                              {polda.name}
                              <button
                                onClick={() => toggleExpand(polda.id)}
                                className="ml-2 focus:outline-none"
                              >
                                {expandedPolda[polda.id] ? (
                                  <ChevronUp size={16} />
                                ) : (
                                  <ChevronDown size={16} />
                                )}
                              </button>
                            </Label>
                            {expandedPolda[polda.id] && (
                              <div className="ml-6 mt-2">
                                <Label className="block">
                                  <Checkbox
                                    checked={polda?.subDestination?.every(
                                      (polres: any) =>
                                        checkedLevels.has(polres.id)
                                    )}
                                    onCheckedChange={(isChecked) => {
                                      const updatedLevels = new Set(
                                        checkedLevels
                                      );
                                      polda?.subDestination?.forEach(
                                        (polres: any) => {
                                          if (isChecked) {
                                            updatedLevels.add(polres.id);
                                          } else {
                                            updatedLevels.delete(polres.id);
                                          }
                                        }
                                      );
                                      setCheckedLevels(updatedLevels);
                                    }}
                                    className="mr-2"
                                  />
                                  Pilih Semua Polres
                                </Label>
                                {polda?.subDestination?.map((polres: any) => (
                                  <Label key={polres.id} className="block mt-1">
                                    <Checkbox
                                      checked={checkedLevels.has(polres.id)}
                                      onCheckedChange={() =>
                                        handleCheckboxChange(polres.id)
                                      }
                                      className="mr-2"
                                    />
                                    {polres.name}
                                  </Label>
                                ))}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </DialogContent>
                  </Dialog>
                </div>
              </div>
            </div>

            <div>
              <p className="font-medium">Nama Acara</p>
              <Controller
                control={control}
                name="title"
                render={({ field }) => (
                  <Input
                    size={"md"}
                    type="text"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Masukan Judul"
                  />
                )}
              />
              {errors.title?.message && (
                <p className="text-red-400 text-sm">{errors.title.message}</p>
              )}
            </div>

            <div className="border-2 border-dashed rounded-md p-4 flex flex-col items-center justify-center text-center text-sm text-muted-foreground">
              <svg
                className="w-6 h-6 mb-2 text-blue-500"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1M12 12v9m0-9l3 3m-3-3l-3 3m6-11a4 4 0 00-8 0v1H4a2 2 0 00-2 2v4h20v-4a2 2 0 00-2-2h-4v-1z"
                />
              </svg>
              <div>
                Drag your file(s) or{" "}
                <span className="text-blue-500 underline cursor-pointer">
                  browse
                </span>
              </div>
              <div className="text-xs mt-1">Max 10 MB files are allowed</div>
            </div>

            <div>
              <p className="font-medium">Deskripsi</p>
              <Controller
                control={control}
                name="description"
                render={({ field }) => (
                  <Textarea
                    rows={3}
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Masukan lokasi"
                  />
                )}
              />
              {errors.description?.message && (
                <p className="text-red-400 text-sm">
                  {errors.description?.message}
                </p>
              )}
            </div>

            <div className="text-right">
              <Button
                type="submit"
                className="bg-blue-600 text-white hover:bg-blue-700"
              >
                Submit
              </Button>
            </div>
          </div>
        </form>
      </Card>
    </div>
  );
}
