"use client";
import React, { 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 {
  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 { Switch } from "@/components/ui/switch";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { addDays, format, setDate } from "date-fns";
import { DateRange } from "react-day-picker";
import TimePicker from "react-time-picker";
import "react-time-picker/dist/TimePicker.css";
import "react-clock/dist/Clock.css";
import { register } from "module";
import MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";

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

export default function FormPressConference() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const editor = useRef(null);
  const [isLiveStreamingEnabled, setIsLiveStreamingEnabled] = useState(false);
  type TaskSchema = z.infer<typeof taskSchema>;
  const [startTime, setStartTime] = useState("08:00");
  const [endTime, setEndTime] = useState("09:00");

  const [date, setDate] = React.useState<DateRange | undefined>({
    from: new Date(2024, 0, 1),
  });

  const handleStartTime = (e: any) => {
    setStartTime(e.target.value);
  };

  const handleEndTime = (e: any) => {
    setEndTime(e.target.value);
  };
  // State for various form fields
  const [output, setOutput] = useState({
    all: false,
    video: false,
    audio: false,
    image: false,
    text: false,
  });

  const [assignmentType, setAssignmentType] = useState("mediahub");
  const [assignmentCategory, setAssignmentCategory] = useState("publication");

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

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

  const save = async (data: TaskSchema) => {
    const requestData = {
      ...data,
      output,
      assignmentType,
      assignmentCategory,
      target: selectedTarget,
      unitSelection,
    };

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

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

  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 (
    <div className="flex flex-col lg:flex-row gap-2">
      <Card className="w-full lg:w-9/12">
        <div className="px-6 py-6">
          <p className="text-lg font-semibold mb-3">Form Konferensi Pers</p>
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className=" gap-5 mb-5">
              {/* Input Title */}
              <div className="space-y-2">
                <Label>Judul Kegiatan</Label>
                <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="flex flex-row items-center">
                <div className="mt-5">
                  <Label>Live Streaming</Label>
                  <div className="flex items-center gap-3">
                    <p>Aktifkan fitur live streaming</p>
                    <Switch
                      defaultChecked={isLiveStreamingEnabled}
                      color="primary"
                      id="c2"
                      onCheckedChange={(checked) =>
                        setIsLiveStreamingEnabled(checked)
                      }
                    />
                  </div>
                </div>
              </div>

              {isLiveStreamingEnabled && (
                <div className="mt-1">
                  <Controller
                    control={control}
                    name="title"
                    render={({ field }) => (
                      <Input
                        size={"md"}
                        type="text"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Masukan ID youtube"
                      />
                    )}
                  />
                  {errors.title?.message && (
                    <p className="text-red-400 text-sm">
                      {errors.title.message}
                    </p>
                  )}
                </div>
              )}

              <div className="flex flex-col lg:flex-row mt-3 items-start lg:items-center justify-between">
                <div className="flex flex-col ">
                  <Label className="mr-3 mb-1">Tanggal</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        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>
                  <Label htmlFor="title">Rentang Waktu</Label>
                  <div className="">
                    <div className="flex flex-row items-center">
                      <div className="col-6">
                        <Input
                          defaultValue="08:00"
                          type="time"
                          onChange={(e) => handleStartTime(e)}
                        />
                      </div>
                      <div className="col-6">
                        <Input
                          defaultValue="09:00"
                          type="time"
                          onChange={(e) => handleEndTime(e)}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div>
                {/* Kirim setValue ke MapHome */}
                <MapHome
                  draggable
                  setLocation={(location) => setValue("location", location)}
                />
              </div>
              <div>
                <Controller
                  control={control}
                  name="location"
                  render={({ field }) => (
                    <Textarea
                      rows={3}
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Masukan lokasi"
                    />
                  )}
                />
                <div className="invalid-feedback">
                  {errors.location?.message}
                </div>
              </div>
              <p className="text-sm my-2 font-semibold">DI SAMPAIKAN OLEH</p>
              <div className="flex flex-col ">
                <div className="mt-1">
                  <Label>Nama Pangkat</Label>
                  <Controller
                    control={control}
                    name="rankName"
                    render={({ field }) => (
                      <Input
                        size={"md"}
                        type="text"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Masukan Nama Pangkat"
                      />
                    )}
                  />
                  {errors.rankName?.message && (
                    <p className="text-red-400 text-sm">
                      {errors.rankName.message}
                    </p>
                  )}
                </div>
              </div>
              <div className="flex flex-col my-3">
                <div className="mt-1">
                  <Label>Nama Lengkap</Label>
                  <Controller
                    control={control}
                    name="fullName"
                    render={({ field }) => (
                      <Input
                        size={"md"}
                        type="text"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Masukan Nama Lengkap"
                      />
                    )}
                  />
                  {errors.fullName?.message && (
                    <p className="text-red-400 text-sm">
                      {errors.fullName.message}
                    </p>
                  )}
                </div>
              </div>
            </div>

            {/* Submit Button */}
            <div className="mt-4">
              <Button type="submit" color="primary">
                Submit
              </Button>
            </div>
          </form>
        </div>
      </Card>
      <Card className="w-full lg:w-3/12">
        <div className="px-3 py-3">Jadwal Selanjutnya</div>
      </Card>
    </div>
  );
}
