"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 { useRouter } from "next/navigation";

import JoditEditor from "jodit-react";
import {
  getCuratorUser,
  getTicketingPriority,
  saveTicketingInternal,
} from "@/service/communication/communication";
import makeAnimated from "react-select/animated";
import Select from "react-select";
import {
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@radix-ui/react-select";
import { SelectGroup } from "@/components/ui/select";

const taskSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  naration: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
});

interface Option {
  id: string;
  label: string;
  value: string;
  fullname: string;
  userLevel: string;
  userLevelId: string;
}

export default function FormInternal() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const editor = useRef(null);
  type TaskSchema = z.infer<typeof taskSchema>;

  // State for various form fields
  const [taskOutput, setTaskOutput] = useState({
    all: false,
    video: false,
    audio: false,
    image: false,
    text: false,
  });

  const [assignmentType, setAssignmentType] = useState("mediahub");
  const [assignmentCategory, setAssignmentCategory] = useState("publication");
  const [mainType, setMainType] = useState<number>(1); // untuk Tipe Penugasan
  const [type, setType] = useState<string>("1");
  const [options, setOptions] = useState<Option[]>([]);
  const [ticketPriority, setTicketPriority] = useState([]);
  const [selectedOption, setSelectedOption] = useState<Option | undefined>(
    undefined
  );
  const animatedComponent = makeAnimated();
  const [platformTypeVisible, setPlatformTypeVisible] = useState(false);
  const [selectedTarget, setSelectedTarget] = useState("");

  // Opsi untuk dropdown
  const priority = [
    { value: "low", label: "Low" },
    { value: "medium", label: "Medium" },
    { value: "high", label: "High" },
  ];

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

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

    setPlatformTypeVisible(selectedValue === 2);
  };

  useEffect(() => {
    getUser();
    getTicketPriority();
  });

  const handleChange = (e: any) => {
    const selected = e;
    setSelectedOption(selected);
  };

  const formatOptionLabel = (option: Option) => (
    <>
      <div className="row">
        <div className="col">
          {option.value} | {option.fullname}
        </div>
      </div>
      <div className="row">
        <div className="col">
          <b>{option.userLevel}</b>
        </div>
      </div>
    </>
  );

  async function getTicketPriority() {
    const res = await getTicketingPriority();

    if (res?.data !== null) {
      const rawData = res?.data?.data;
      setTicketPriority(rawData);
    }
  }

  async function getUser() {
    const res = await getCuratorUser();

    if (res?.data !== null) {
      const rawUser = res?.data?.data?.content;
      console.log("raw user", rawUser);

      // Tentukan tipe array sebagai Option[]
      const optionArr: Option[] = rawUser.map((option: any) => ({
        id: option?.id,
        label: option?.username + option?.fullname + option?.userLevel?.name,
        value: option?.username,
        fullname: option?.fullname,
        userLevel: option?.userLevel?.name,
        userLevelId: option?.userLevel?.id,
      }));

      setOptions(optionArr);
    }
  }

  const save = async (data: TaskSchema) => {
    const requestData = {
      title: data.title,
      narration: data.naration,
      target: selectedTarget,
      sendToId: selectedOption?.id, // This should work now without the error
    };

    const response = await saveTicketingInternal(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/communication");
    });
  };

  const onSubmit = (data: TaskSchema) => {
    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 Penugasan</p>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5">
            {/* Input Title */}
            <div className="space-y-2">
              <Label>Judul</Label>
              <Controller
                control={control}
                name="title"
                render={({ field }) => (
                  <Input
                    size="md"
                    type="text"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Enter Title"
                  />
                )}
              />
              {errors.title?.message && (
                <p className="text-red-400 text-sm">{errors.title.message}</p>
              )}
            </div>
            <div className="w-full">
              <div className="mt-5">
                <Label>Priority</Label>
                <Select
                  id="target-select"
                  options={priority}
                  onChange={(selectedOption) =>
                    setSelectedTarget(selectedOption?.value || "")
                  }
                  placeholder="Pilih"
                  styles={{
                    control: (base) => ({
                      ...base,
                      minHeight: "40px", // Ukuran sesuai dengan size="md"
                    }),
                  }}
                />
              </div>
            </div>
            <div className="w-full">
              <div className="mt-5">
                <Label>Ditunjukan Untuk</Label>
                <Select
                  options={options}
                  className="w-100"
                  closeMenuOnSelect={false}
                  components={animatedComponent}
                  onChange={handleChange}
                  formatOptionLabel={formatOptionLabel}
                  isMulti={false}
                />
              </div>
            </div>
            <div className="mt-5">
              <Label>Narasi Penugasan</Label>
              <Controller
                control={control}
                name="naration"
                render={({ field: { onChange, value } }) => (
                  <JoditEditor
                    ref={editor}
                    value={value}
                    onChange={onChange}
                    className="dark:text-black"
                  />
                )}
              />
              {errors.naration?.message && (
                <p className="text-red-400 text-sm">
                  {errors.naration.message}
                </p>
              )}
            </div>
          </div>

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