"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";
import { error } from "@/lib/swal";
import Cookies from "js-cookie";
import { postSchedule } from "@/service/schedule/schedule";

const taskSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  level: z.string().min(1, { message: "Judul diperlukan" }),
  name: z.string().min(1, { message: "Judul diperlukan" }),
  location: z.string().min(1, { message: "Judul diperlukan" }),
});

export default function FormPressRelease() {
  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 [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 = {
      title: data.title,
      address: data.location,
      speakerTitle: data.level,
      speakerName: data.name,
      startTime, // Start time from state
      endTime, // End time from state
      addressLat: "0.0", // Replace with actual latitude
      addressLong: "0.0", // Replace with actual longitude
      startDate: date?.from ? format(date.from, "yyyy-MM-dd") : null,
      endDate: date?.to ? format(date.to, "yyyy-MM-dd") : null,
      isYoutube: isLiveStreamingEnabled,
      scheduleTypeId: 3,
    };

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

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

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

    // Optional: Use Swal for success feedback
    MySwal.fire({
      title: "Sukses",
      text: "Data berhasil disimpan.",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then(() => {
      router.push("/en/contributor/schedule/press-release");
    });
  };

  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 Pers Rilis</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>
              <div className="mt-5">
                <Label>Invitation</Label>
                <Select onValueChange={setSelectedTarget}>
                  <SelectTrigger size="md">
                    <SelectValue placeholder="Pilih" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="kompas">
                      PT. kompas Cyber Media{" "}
                    </SelectItem>
                    <SelectItem value="trans">
                      PT. Trans Digital Media
                    </SelectItem>
                    <SelectItem value="mnc">MNC</SelectItem>
                  </SelectContent>
                </Select>
              </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="level"
                    render={({ field }) => (
                      <Input
                        size={"md"}
                        type="text"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Masukan Nama Pangkat"
                      />
                    )}
                  />
                  {errors.level?.message && (
                    <p className="text-red-400 text-sm">
                      {errors.level.message}
                    </p>
                  )}
                </div>
              </div>
              <div className="flex flex-col my-3">
                <div className="mt-1">
                  <Label>Nama Lengkap</Label>
                  <Controller
                    control={control}
                    name="name"
                    render={({ field }) => (
                      <Input
                        size={"md"}
                        type="text"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Masukan Nama Lengkap"
                      />
                    )}
                  />
                  {errors.name?.message && (
                    <p className="text-red-400 text-sm">
                      {errors.name.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>
  );
}
