"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";

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

export default function FormTask() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const editor = useRef(null);
  type TaskSchema = z.infer<typeof taskSchema>;

  // 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,
    formState: { errors },
  } = useForm<TaskSchema>({
    resolver: zodResolver(taskSchema),
  });

  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 (
    <Card>
      <div className="px-6 py-6">
        <p className="text-lg font-semibold mb-3">Form Penugasan</p>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5">
            {/* Input Title */}
            <div className="space-y-2">
              <Label>Judul</Label>
              <Controller
                control={control}
                name="title"
                render={({ field }) => (
                  <Input
                    size="md"
                    type="text"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Enter Title"
                  />
                )}
              />
              {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>Tujuan Pemilihan Tugas</Label>
                <Select onValueChange={setSelectedTarget}>
                  <SelectTrigger size="md">
                    <SelectValue placeholder="Pilih" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Semua Pengguna</SelectItem>
                    <SelectItem value="contributor">Kontributor</SelectItem>
                    <SelectItem value="approver">Approver</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex flex-wrap gap-3 mt-5 pt-5 ml-3">
                {Object.keys(unitSelection).map((key) => (
                  <div className="flex items-center gap-2" key={key}>
                    <Checkbox
                      id={key}
                      checked={unitSelection[key as keyof typeof unitSelection]}
                      onCheckedChange={(value) =>
                        setUnitSelection({ ...unitSelection, [key]: value })
                      }
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            <div className="mt-5">
              <Label>Tipe Penugasan</Label>
              <RadioGroup
                value={assignmentType}
                onValueChange={setAssignmentType}
                className="flex flex-wrap gap-6"
              >
                <RadioGroupItem value="mediahub" id="mediahub" />
                <Label htmlFor="mediahub">Mediahub</Label>
                <RadioGroupItem value="medsos-mediahub" id="medsos-mediahub" />
                <Label htmlFor="medsos-mediahub">Medsos Mediahub</Label>
              </RadioGroup>
            </div>

            {/* RadioGroup Assignment Category */}
            <div className="mt-5">
              <Label>Jenis Penugasan</Label>
              <RadioGroup
                value={assignmentCategory}
                onValueChange={setAssignmentCategory}
                className="flex flex-wrap gap-6"
              >
                <RadioGroupItem value="publication" id="publication" />
                <Label htmlFor="publication">Publikasi</Label>
                <RadioGroupItem value="amplification" id="amplification" />
                <Label htmlFor="amplification">Amplifikasi</Label>
                <RadioGroupItem value="contra" id="contra" />
                <Label htmlFor="contra">Kontra</Label>
              </RadioGroup>
            </div>
            <div className="mt-5">
              <Label>Output Tugas</Label>
              <div className="flex flex-wrap gap-3">
                {Object.keys(output).map((key) => (
                  <div className="flex items-center gap-2" key={key}>
                    <Checkbox
                      id={key}
                      checked={output[key as keyof typeof output]}
                      onCheckedChange={(value) =>
                        setOutput({ ...output, [key]: value })
                      }
                    />
                    <Label htmlFor={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1)}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            <div className="mt-5">
              <Label>Narasi Penugasan</Label>
              <Controller
                control={control}
                name="naration"
                render={({ field: { onChange, value } }) => (
                  <JoditEditor
                    ref={editor}
                    value={value}
                    onChange={onChange}
                    className="dark:text-black"
                  />
                )}
              />
              {errors.naration?.message && (
                <p className="text-red-400 text-sm">
                  {errors.naration.message}
                </p>
              )}
            </div>
          </div>

          {/* Submit Button */}
          <div className="mt-4">
            <Button type="submit" color="primary">
              Submit
            </Button>
          </div>
        </form>
      </div>
    </Card>
  );
}
