"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { getScheduleById, updateSchedule } from "@/service/landing/landing";

const MySwal = withReactContent(Swal);

export default function EditSchedulePage() {
  const router = useRouter();
  const { id } = useParams();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState({
    description: "",
    endDate: "",
    endTime: "",
    isLiveStreaming: false,
    liveStreamingUrl: "",
    location: "",
    posterImagePath: "",
    speakers: "",
    startDate: "",
    startTime: "",
    statusId: 1,
    title: "",
    typeId: 1,
  });

  // Fetch existing schedule data
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await getScheduleById(id as string);
        if (!res.error && res.data) {
          const data = res.data.data || res.data;
          setFormData({
            description: data.description || "",
            endDate: data.endDate
              ? new Date(data.endDate).toISOString().slice(0, 10)
              : "",
            endTime: data.endDate
              ? new Date(data.endDate).toISOString().slice(11, 16)
              : "",
            isLiveStreaming: data.isLiveStreaming || false,
            liveStreamingUrl: data.liveStreamingUrl || "",
            location: data.location || "",
            posterImagePath: data.posterImagePath || "",
            speakers: data.speakers || "",
            startDate: data.startDate
              ? new Date(data.startDate).toISOString().slice(0, 10)
              : "",
            startTime: data.startDate
              ? new Date(data.startDate).toISOString().slice(11, 16)
              : "",
            statusId: data.statusId || 1,
            title: data.title || "",
            typeId: data.typeId || 1,
          });
        } else {
          MySwal.fire({
            icon: "error",
            title: "Gagal",
            text: res.message || "Data tidak ditemukan.",
          });
        }
      } catch (error) {
        MySwal.fire({
          icon: "error",
          title: "Error",
          text: "Terjadi kesalahan saat memuat data.",
        });
        console.error(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [id]);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleToggle = (checked: boolean) => {
    setFormData((prev) => ({ ...prev, isLiveStreaming: checked }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const payload = {
        ...formData,
        startDate: `${formData.startDate}T${formData.startTime}:00Z`,
        endDate: `${formData.endDate}T${formData.endTime}:00Z`,
      };

      const res = await updateSchedule(id as string, payload);

      if (!res?.error) {
        MySwal.fire({
          icon: "success",
          title: "Berhasil!",
          text: "Jadwal berhasil diperbarui.",
          timer: 2000,
          showConfirmButton: false,
        });
        setTimeout(() => router.push("/admin/schedule"), 2000);
      } else {
        MySwal.fire({
          icon: "error",
          title: "Gagal!",
          text: res.message || "Gagal memperbarui jadwal.",
        });
      }
    } catch (error) {
      MySwal.fire({
        icon: "error",
        title: "Error",
        text: "Terjadi kesalahan pada sistem.",
      });
      console.error(error);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-[70vh] text-muted-foreground">
        Memuat data jadwal...
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto mt-10">
      <Card className="shadow-lg border border-gray-200 dark:border-gray-800">
        <CardHeader>
          <CardTitle className="text-xl font-semibold">
            Edit Jadwal
          </CardTitle>
        </CardHeader>

        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <Label htmlFor="title">Judul Acara</Label>
              <Input
                id="title"
                name="title"
                value={formData.title}
                onChange={handleChange}
                placeholder="Masukkan judul acara"
                required
              />
            </div>

            <div>
              <Label htmlFor="description">Deskripsi</Label>
              <Textarea
                id="description"
                name="description"
                value={formData.description}
                onChange={handleChange}
                placeholder="Masukkan deskripsi acara"
                required
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="startDate">Tanggal Mulai</Label>
                <Input
                  type="date"
                  id="startDate"
                  name="startDate"
                  value={formData.startDate}
                  onChange={handleChange}
                  required
                />
              </div>
              <div>
                <Label htmlFor="endDate">Tanggal Selesai</Label>
                <Input
                  type="date"
                  id="endDate"
                  name="endDate"
                  value={formData.endDate}
                  onChange={handleChange}
                  required
                />
              </div>
              <div>
                <Label htmlFor="startTime">Jam Mulai</Label>
                <Input
                  type="time"
                  id="startTime"
                  name="startTime"
                  value={formData.startTime}
                  onChange={handleChange}
                  required
                />
              </div>
              <div>
                <Label htmlFor="endTime">Jam Selesai</Label>
                <Input
                  type="time"
                  id="endTime"
                  name="endTime"
                  value={formData.endTime}
                  onChange={handleChange}
                  required
                />
              </div>
            </div>

            <div>
              <Label htmlFor="location">Lokasi</Label>
              <Input
                id="location"
                name="location"
                value={formData.location}
                onChange={handleChange}
                placeholder="Masukkan lokasi acara"
                required
              />
            </div>

            <div>
              <Label htmlFor="speakers">Pembicara</Label>
              <Input
                id="speakers"
                name="speakers"
                value={formData.speakers}
                onChange={handleChange}
                placeholder="Nama pembicara"
                required
              />
            </div>

            <div className="flex items-center justify-between">
              <Label htmlFor="isLiveStreaming">Live Streaming?</Label>
              <Switch
                id="isLiveStreaming"
                checked={formData.isLiveStreaming}
                onCheckedChange={handleToggle}
              />
            </div>

            {formData.isLiveStreaming && (
              <div>
                <Label htmlFor="liveStreamingUrl">Link Live Streaming</Label>
                <Input
                  id="liveStreamingUrl"
                  name="liveStreamingUrl"
                  value={formData.liveStreamingUrl}
                  onChange={handleChange}
                  placeholder="https://youtube.com/..."
                />
              </div>
            )}

            <div>
              <Label htmlFor="posterImagePath">Poster (opsional)</Label>
              <Input
                id="posterImagePath"
                name="posterImagePath"
                value={formData.posterImagePath}
                onChange={handleChange}
                placeholder="/uploads/poster/namafile.png"
              />
            </div>

            <Button
              type="submit"
              className="w-full h-11 font-semibold"
              disabled={saving}
            >
              {saving ? "Menyimpan..." : "Simpan Perubahan"}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
