"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 { 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, parseISO, 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 MapHome from "@/components/maps/MapHome";
import { Textarea } from "@/components/ui/textarea";
import { error, loading } from "@/lib/swal";
import Cookies from "js-cookie";
import { detailSchedule, 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" }),
});

interface Detail {
  id: number;
  title: string;
  address: string;
  speakerTitle: string;
  speakerName: string;
  addressLat: number;
  addressLong: number;
}

export default function FormEventUpdate() {
  const { id } = useParams() as { id: string };
  console.log(id);
  const router = useRouter();
  const MySwal = withReactContent(Swal);
  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] = useState<DateRange | undefined>();

  const [detail, setDetail] = useState<Detail>();
  const [refresh, setRefresh] = useState(false);

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

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

        setDetail(details);
        if (details) {
          setDate({
            from: parseISO(details.startDate),
            to: parseISO(details.endDate),
          });
        }
        if (details) {
          setStartTime(details.startTime);
          setEndTime(details.endTime);
        }
      }
    }
    initState();
  }, [refresh, setValue]);

  const handleStartTime = (e: React.ChangeEvent<HTMLInputElement>) => {
    setStartTime(e.target.value);
  };

  const handleEndTime = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEndTime(e.target.value);
  };

  const save = async (data: TaskSchema) => {
    const requestData: {
      id?: number;
      title: string;
      address: string;
      speakerTitle: string;
      speakerName: string;
      startTime: string;
      endTime: string;
      addressLat: string;
      addressLong: string;
      startDate: string | null;
      endDate: string | null;
      isYoutube: boolean;
      scheduleTypeId: number;
    } = {
      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: 2,
    };

    // Add id property if it exists
    if (id) {
      requestData.id = parseInt(id, 10); // Ensure id is a number
    }

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

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

  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 Event</p>
          <form onSubmit={handleSubmit(onSubmit)}>
            {detail !== undefined ? (
              <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
                        type="text"
                        defaultValue={detail?.title}
                        onChange={field.onChange}
                      />
                    )}
                  />
                  {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>
                      <div className="flex flex-row items-center">
                        <div className="col-6">
                          <Input
                            value={startTime}
                            type="time"
                            onChange={handleStartTime}
                          />
                        </div>
                        <div className="col-6">
                          <Input
                            value={endTime}
                            type="time"
                            onChange={handleEndTime}
                          />
                        </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}
                        defaultValue={detail?.address}
                        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="level"
                      render={({ field }) => (
                        <Input
                          size={"md"}
                          type="text"
                          defaultValue={detail?.speakerTitle}
                          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"
                          defaultValue={detail?.speakerName}
                          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>
  );
}
