"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 {
  createTask,
  createTaskTa,
  getTask,
  getUserLevelForAssignments,
  getUserLevelForExpert,
} from "@/service/task";
import { useTranslations } from "next-intl";
import dynamic from "next/dynamic";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import { Link } from "@/i18n/routing";

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

interface FileWithPreview extends File {
  preview: string;
}

export type taskDetail = {
  id: number;
  title: string;
  fileTypeOutput: string;
  assignedToTopLevel: string;
  url: string;
};

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

export default function FormMediaOnline() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const editor = useRef(null);
  type TaskSchema = z.infer<typeof taskSchema>;
  const { id } = useParams() as { id: string };
  console.log(id);
  const [taskType, setTaskType] = useState<string>("atensi-khusus");
  const [broadcastType, setBroadcastType] = useState<string>("");
  const [type, setType] = useState<string>("1");
  const [selectedTarget, setSelectedTarget] = useState("3,4");
  const [detail, setDetail] = useState<taskDetail>();
  const [listExpert, setListExpert] = useState<any[]>([]);
  const [checkedLevels, setCheckedLevels] = useState<Set<number>>(new Set());
  const [expandedPolda, setExpandedPolda] = useState([{}]);
  const [isLoading, setIsLoading] = useState(false);
  const [audioFile, setAudioFile] = useState<File | null>(null);
  const [isRecording, setIsRecording] = useState(false);
  const [timer, setTimer] = useState<number>(120);

  const t = useTranslations("Form");

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

  // };

  const save = async (data: TaskSchema) => {
    const requestData: {
      id?: number;
      title: string;
      assignedToUsers: any;
      url: any;
    } = {
      ...data,
      assignedToUsers: data.assign,
      url: data.url,
      title: data.title,
    };

    const response = await createTaskTa(requestData);

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

    const id = response?.data?.data.id;
  };

  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);
      }
    });
  };

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

  return (
    <Card>
      <div className="px-6 py-6">
        <p className="text-xl mb-3">{t("data-media", { defaultValue: "Data Media" })}</p>
        <p className="text-lg font-semibold mb-3">{t("form-media", { defaultValue: "Form Media" })}</p>

        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5">
            {/* Input Title */}
            <div className="space-y-2">
              <Label>{t("title-media-online", { defaultValue: "Title Media Online" })}</Label>
              <Controller
                control={control}
                name="title"
                render={({ field }) => (
                  <Input
                    size="md"
                    type="text"
                    value={detail?.title}
                    onChange={field.onChange}
                    placeholder="Enter Title"
                  />
                )}
              />
              {errors.title?.message && (
                <p className="text-red-400 text-sm">{errors.title.message}</p>
              )}
            </div>

            <div className="mt-5 space-y-2">
              <Label>{t("url", { defaultValue: "Url" })}</Label>
              <Controller
                control={control}
                name="url"
                render={({ field }) => (
                  <Input
                    size="md"
                    type="text"
                    value={detail?.url}
                    onChange={field.onChange}
                    placeholder="Enter Title"
                  />
                )}
              />
              {errors.title?.message && (
                <p className="text-red-400 text-sm">{errors.title.message}</p>
              )}
            </div>
            <div className="mt-5 space-y-2">
              <Label>{t("coverage-area", { defaultValue: "Coverage Area" })}</Label>
              <Select onValueChange={setSelectedTarget}>
                <SelectTrigger size="md">
                  <SelectValue placeholder="Choose" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="3,4">Semua Pengguna</SelectItem>
                  <SelectItem value="4">Kontributor</SelectItem>
                  <SelectItem value="3">Approver</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex flex-row items-center justify-end gap-3">
            <div className="mt-4 ">
              <Link href={"/admin/media-tracking/media-online"}>
                <Button color="primary" variant={"outline"}>
                  {t("cancel", { defaultValue: "Cancel" })}
                </Button>
              </Link>
            </div>
            <div className="mt-4">
              <Button type="submit" color="primary">
                {t("submit", { defaultValue: "Submit" })}
              </Button>
            </div>
          </div>
        </form>
      </div>
    </Card>
  );
}
