"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import JoditEditor from "jodit-react";
import {
  createTask,
  getTask,
  getUserLevelForAssignments,
} from "@/service/task";
import { getContestById, postCreateContest } from "@/service/contest/contest";
import page from "@/app/[locale]/page";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, ChevronDown, ChevronUp } from "lucide-react";
import { format, parseISO } from "date-fns";
import { Calendar } from "@/components/ui/calendar";
import { DateRange } from "react-day-picker";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import dynamic from "next/dynamic";
import Cookies from "js-cookie";

const contestSchema = z.object({
  theme: z.string().min(1, { message: "Judul diperlukan" }),
  hastagCode: z.string().min(1, { message: "Judul diperlukan" }),
  description: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
  scoringFormula: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
});

export type contestDetail = {
  id: number;
  theme: string;
  hastagCode: string;
  assignedToTopLevel: string;
  assignmentType: {
    id: number;
    name: string;
  };
  assignmentMainType: {
    id: number;
    name: string;
  };
  createdAt: string;
  platformType: string | null;
  assignmentTypeId: string;
  targetOutput: string;
  targetParticipantTopLevel: string;
  description: string;
  fileTypeOutput: any;
  is_active: string;
};

const CustomEditor = dynamic(
  () => {
    return import("@/components/editor/custom-editor");
  },
  { ssr: false }
);

export default function FormContestDetail() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const editor = useRef(null);
  type ContestSchema = z.infer<typeof contestSchema>;
  const { id } = useParams() as { id: string };
  console.log(id);
  const [mainType, setMainType] = useState<string>("1");
  const [broadcastType, setBroadcastType] = useState<string>(""); // untuk Tipe Penugasan
  const [selectedTarget, setSelectedTarget] = useState("all");
  const [detail, setDetail] = useState<any>();
  const [refresh] = useState(false);
  const [date, setDate] = useState<DateRange | undefined>();
  const [listDest, setListDest] = useState([]);
  const [checkedLevels, setCheckedLevels] = useState(new Set());
  const [expandedPolda, setExpandedPolda] = useState([{}]);
  const [isLoading, setIsLoading] = useState(false);

  const [platformTypeVisible, setPlatformTypeVisible] = useState(false);

  const [taskOutput, setTaskOutput] = useState({
    all: false,
    video: false,
    audio: false,
    image: false,
    text: false,
  });

  const [unitSelection, setUnitSelection] = useState({
    allUnit: false,
    mabes: false,
    polda: false,
    polres: false,
  });

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<ContestSchema>({
    resolver: zodResolver(contestSchema),
  });

  // const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   const selectedValue = Number(event.target.value);
  //   setMainType(selectedValue);

  //   setPlatformTypeVisible(selectedValue === 2);
  // };

  useEffect(() => {
    async function fetchPoldaPolres() {
      setIsLoading(true);
      try {
        const response = await getUserLevelForAssignments();
        setListDest(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();
  }, []);

  useEffect(() => {
    async function initState() {
      if (id) {
        const response = await getContestById(id);
        const details = response?.data?.data;

        setDetail(details);
        if (details?.createdAt) {
          const parsedDate = parseISO(details.createdAt);
          setDate({ from: parsedDate, to: parsedDate });
        }
      }
    }
    initState();
  }, [id, refresh]);

  useEffect(() => {
    if (detail?.targetOutput) {
      const outputSet = new Set(detail.targetOutput.split(",").map(Number)); // Membagi string ke dalam array dan mengonversi ke nomor
      setTaskOutput({
        all: outputSet.has(0),
        video: outputSet.has(2),
        audio: outputSet.has(4),
        image: outputSet.has(1),
        text: outputSet.has(3),
      });
    }
  }, [detail?.targetOutput]);

  // useEffect(() => {
  //   if (detail?.targetParticipantTopLevel) {
  //     const outputSet = new Set(
  //       detail.targetParticipantTopLevel.split(",").map(Number)
  //     );
  //     setUnitSelection({
  //       allUnit: outputSet.has(0),
  //       mabes: outputSet.has(1),
  //       polda: outputSet.has(2),
  //       polres: outputSet.has(3),
  //     });
  //   }
  // }, [detail?.targetParticipantTopLevel]);

  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 toggleExpand = (poldaId: any) => {
    setExpandedPolda((prev: any) => ({
      ...prev,
      [poldaId]: !prev[poldaId],
    }));
  };

  const save = async (data: ContestSchema) => {
    const fileTypeMapping = {
      all: "1",
      video: "2",
      audio: "3",
      image: "4",
      text: "5",
    };

    const unitMapping = {
      allUnit: "0",
      mabes: "1",
      polda: "2",
      polres: "3",
    };

    const assignmentPurposeString = Object.keys(unitSelection)
      .filter((key) => unitSelection[key as keyof typeof unitSelection])
      .map((key) => unitMapping[key as keyof typeof unitMapping])
      .join(",");

    const selectedOutputs = Object.keys(taskOutput)
      .filter((key) => taskOutput[key as keyof typeof taskOutput]) // Ambil hanya yang `true`
      .map((key) => fileTypeMapping[key as keyof typeof fileTypeMapping]) // Konversi ke nilai string
      .join(",");

    const requestData: {
      id?: any;
      theme: string;
      assignedToLevel: any;
      assignmentPurpose: any;
      hastagCode: string;
      description: string;
      assignmentMainTypeId: any;
      scoringFormula: string;
      fileTypeOutput: any;
    } = {
      ...data,
      hastagCode: data.hastagCode,
      theme: data.theme,
      description: data.description,
      scoringFormula: data.scoringFormula,
      assignmentMainTypeId: mainType,
      assignedToLevel: handlePoldaPolresChange(),
      assignmentPurpose: assignmentPurposeString,
      fileTypeOutput: selectedOutputs,
    };

    if (id != undefined) {
      requestData.id = id;
    }

    const response = await postCreateContest(requestData);

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

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

  const onSubmit = (data: ContestSchema) => {
    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 (
    <Card>
      <div className="px-6 py-6">
        <p className="text-lg font-semibold mb-3">Form Contest</p>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5">
            <div className="space-y-2">
              <Label>Kode Lomba</Label>
              <Controller
                control={control}
                name="hastagCode"
                render={({ field: { onChange, value } }) => (
                  <Input
                    size="md"
                    type="text"
                    value={detail?.hastagCode || value}
                    onChange={onChange}
                    placeholder="Enter hastagCode"
                  />
                )}
              />
              {errors.hastagCode?.message && (
                <p className="text-red-400 text-sm">
                  {errors.hastagCode.message}
                </p>
              )}
            </div>
            {/* Input Title */}
            <div className="space-y-2 mt-5">
              <Label>Judul Lomba</Label>
              <Controller
                control={control}
                name="theme"
                render={({ field: { onChange, value } }) => (
                  <Input
                    size="md"
                    type="text"
                    value={detail?.theme || value}
                    onChange={onChange}
                    placeholder="Enter theme"
                  />
                )}
              />
              {errors.theme?.message && (
                <p className="text-red-400 text-sm">{errors.theme.message}</p>
              )}
            </div>
            <div className="flex flex-col mt-5">
              <Label className="mr-3 mb-1">Tanggal</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    value={detail?.createdAt}
                    id="date"
                    variant={"outline"}
                    className={cn(
                      "w-[280px] lg:w-[300px] justify-start text-left font-normal",
                      !date && "text-muted-foreground"
                    )}
                  >
                    <CalendarIcon />
                    {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 className="mt-5">
              <Label>Output Lomba</Label>
              <div className="flex flex-wrap gap-3 mt-2">
                {Object.keys(taskOutput).map((key) => (
                  <div className="flex items-center gap-2" key={key}>
                    <Checkbox
                      id={key}
                      checked={taskOutput[key as keyof typeof taskOutput]}
                      onCheckedChange={(value) =>
                        setTaskOutput({ ...taskOutput, [key]: value })
                      }
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            <div className="flex flex-col mt-7">
              <Label>Pelaksana Tugas</Label>
              <div className="flex flex-row mt-2 gap-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) =>
                        setUnitSelection({ ...unitSelection, [key]: value })
                      }
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
                <div className="  pl-1">
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button variant="soft" size="sm" color="primary">
                        [Kustom]
                      </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 className="mt-7">
              <Label>Narasi Penugasan</Label>
              <Controller
                control={control}
                name="description"
                render={({ field: { onChange, value } }) => (
                  <CustomEditor
                    onChange={onChange}
                    initialData={detail?.description || value}
                  />
                )}
              />
              {errors.description?.message && (
                <p className="text-red-400 text-sm">
                  {errors.description.message}
                </p>
              )}
            </div>
            <div className="mt-7">
              <Label>Rumus Penilaian</Label>
              <Controller
                control={control}
                name="scoringFormula"
                render={({ field: { onChange, value } }) => (
                  <CustomEditor
                    onChange={onChange}
                    initialData={detail?.scoringFormula || value}
                  />
                )}
              />
              {errors.scoringFormula?.message && (
                <p className="text-red-400 text-sm">
                  {errors.scoringFormula.message}
                </p>
              )}
            </div>
          </div>

          <div className="mt-4">
            <Button type="submit" color="primary">
              Submit
            </Button>
          </div>
        </form>
      </div>
    </Card>
  );
}
