"use client";

import { useState } from "react";
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 { useRouter } from "next/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { createSchedule } from "@/service/landing/landing";

const MySwal = withReactContent(Swal);

export default function CreateSchedulePage() {
  const router = useRouter();

  const [formData, setFormData] = useState({
    createdById: 1, // bisa diganti sesuai ID user login
    description: "",
    endDate: "",
    endTime: "",
    isLiveStreaming: false,
    location: "",
    speakers: "",
    startDate: "",
    startTime: "",
    title: "",
    typeId: 1,
    liveStreamingUrl: "",
    posterImagePath: "",
  });

  const [loading, setLoading] = useState(false);

  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();
    setLoading(true);

    try {
      // Format tanggal sesuai ISO backend (2025-11-01T00:00:00Z)
      const payload = {
        ...formData,
        startDate: `${formData.startDate}T${formData.startTime}:00Z`,
        endDate: `${formData.endDate}T${formData.endTime}:00Z`,
      };

      const res = await createSchedule(payload);

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

  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">
            Buat Jadwal Baru
          </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={loading}
            >
              {loading ? "Menyimpan..." : "Simpan Jadwal"}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
