import React, { useEffect, useState } from "react";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "../ui/dialog";
import FormSurvey from "./survey";
import { Controller, useForm } from "react-hook-form";
import { Textarea } from "../ui/textarea";
import { Button } from "../ui/button";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Checkbox } from "../ui/checkbox";
import { createSurveyData } from "@/service/survey/survey";

const surveySchema = z.object({
  accessFrequency: z.string(),
  uiExperienceDesign: z.string(),
  uiExperienceNavigation: z.string(),
  uiExperienceSpeed: z.string(),
  infoAccuracy: z.string(),
  infoCompleteness: z.string(),
  usefulness: z.string(),
  suggestion: z.string().optional(),
});

type SurveySchema = z.infer<typeof surveySchema>;

const UserSurveyBox = () => {
  const [openPolda, setOpenPolda] = useState<any>();
  const [showSurvey, setShowSurvey] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<SurveySchema>({
    resolver: zodResolver(surveySchema),
    mode: "all",
    defaultValues: {
      accessFrequency: "",
      uiExperienceDesign: "",
      uiExperienceNavigation: "",
      uiExperienceSpeed: "",
      infoAccuracy: "",
      infoCompleteness: "",
      usefulness: "",
      suggestion: "",
    },
  });

  const options = {
    accessFrequency: ["Setiap hari", "Beberapa kali seminggu", "Beberapa kali dalam sebulan", "Baru pertama kali"],
    uiExperienceDesign: ["Sangat baik", "Baik", "Cukup", "Kurang", "Buruk"],
    uiExperienceNavigation: ["Sangat mudah", "Mudah", "Cukup", "Sulit", "Sangat sulit"],
    uiExperienceSpeed: ["Sangat cepat", "Cepat", "Cukup", "Lambat", "Sangat lambat"],
    infoAccuracy: ["Sangat puas", "Puas", "Cukup", "Kurang puas", "Tidak puas"],
    infoCompleteness: ["Sangat lengkap", "Lengkap", "Cukup", "Kurang lengkap", "Tidak lengkap"],
    usefulness: ["Sangat membantu", "Membantu", "Cukup membantu", "Kurang membantu", "Tidak membantu"],
  };

  const renderControllerGroup = (name: keyof SurveySchema, question: string, choices: string[]) => (
    <div className="space-y-2">
      <p className="font-medium">{question}</p>
      <div className="grid grid-cols-2 gap-2">
        {choices.map((choice, i) => (
          <Controller
            key={i}
            name={name}
            control={control}
            render={({ field }) => (
              <label className="flex items-center space-x-2">
                <Checkbox checked={field.value === choice} onCheckedChange={() => field.onChange(choice)} />
                <span>{choice}</span>
              </label>
            )}
          />
        ))}
      </div>
      {errors[name] && <p className="text-red-500 text-sm">{errors[name]?.message as string}</p>}
    </div>
  );

  const onSubmit = async (data: SurveySchema) => {
    setIsLoading(true);
    try {
      const response = await createSurveyData(data);
      console.log("API Response:", response);
      setShowSurvey(false);
      setOpenPolda(false);
    } catch (error) {
      console.error("Error submitting survey:", error);
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <div className="relative mt-8 rounded-lg bg-white dark:bg-zinc-900 p-6 shadow overflow-hidden">
      {/* Garis menyerong */}
      <div className="hidden lg:block absolute right-64 top-0">
        <img src="/assets/line1.png" alt="line" className="" />
      </div>
      <div className="hidden lg:block absolute right-60 top-0">
        <img src="/assets/line1.png" alt="line" className="" />
      </div>
      <div className="hidden lg:block absolute right-56 top-0">
        <img src="/assets/line1.png" alt="line" className="" />
      </div>

      {/* Grid konten */}
      <div className="relative z-10 grid grid-cols-1 md:grid-cols-2 gap-4 items-center">
        {/* Kiri: Teks dan tombol */}
        <div>
          <h2 className="text-2xl font-bold mb-2">SURVEI KEPUASAN PENGGUNA MEDIAHUB POLRI</h2>
          <p className="text-sm text-gray-700 dark:text-gray-300 mb-6">Kami menghargai pendapat Anda! Survei ini bertujuan untuk meningkatkan kualitas layanan MediaHub Polri. Mohon luangkan waktu beberapa menit untuk mengisi survei ini.</p>
          <Dialog open={openPolda} onOpenChange={setOpenPolda}>
            <DialogTrigger asChild>
              <Button size="md" onClick={() => setOpenPolda(true)} className="bg-[#bb3523] hover:bg-[#9e2e1e] text-white font-bold px-6 py-3 rounded shadow-md transition-all duration-300">
                SURVEY SEKARANG
              </Button>
            </DialogTrigger>
            <DialogContent size="md" className="max-h-[90vh] overflow-auto flex flex-col" data-lenis-prevent>
              <DialogHeader>
                <DialogTitle className="text-lg font-bold">SURVEI KEPUASAN PENGGUNA MEDIAHUB POLRI</DialogTitle>
                <DialogDescription className="text-sm">Kami menghargai pendapat Anda! Survei ini bertujuan untuk meningkatkan kualitas layanan MediaHub Polri.</DialogDescription>
              </DialogHeader>

              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 mt-4">
                {renderControllerGroup("accessFrequency", "1. Seberapa sering Anda mengakses MediaHub Polri?", options.accessFrequency)}

                <div>
                  <p className="font-medium">2. Bagaimana pengalaman Anda dalam mengakses website ini?</p>
                  <div className="space-y-3 mt-2">
                    {renderControllerGroup("uiExperienceDesign", "a) Tampilan dan desain website", options.uiExperienceDesign)}
                    {renderControllerGroup("uiExperienceNavigation", "b) Kemudahan navigasi", options.uiExperienceNavigation)}
                    {renderControllerGroup("uiExperienceSpeed", "c) Kecepatan akses website", options.uiExperienceSpeed)}
                  </div>
                </div>

                <div>
                  <p className="font-medium">3. Seberapa puas Anda dengan informasi yang tersedia di MediaHub Polri?</p>
                  <div className="space-y-3 mt-2">
                    {renderControllerGroup("infoAccuracy", "a) Akurat dan terpercaya", options.infoAccuracy)}
                    {renderControllerGroup("infoCompleteness", "b) Kelengkapan berita dan informasi", options.infoCompleteness)}
                  </div>
                </div>

                {renderControllerGroup("usefulness", "4. Apakah Anda merasa website ini membantu dalam mendapatkan informasi terkait Polri?", options.usefulness)}

                <div>
                  <p className="font-medium">5. Apa saran atau masukan Anda?</p>
                  <Controller name="suggestion" control={control} render={({ field }) => <Textarea placeholder="Tulis pesan Anda..." value={field.value} onChange={field.onChange} />} />
                </div>

                <div className="flex justify-end gap-2">
                  <Button variant="outline" onClick={() => setOpenPolda(false)}>
                    Batal
                  </Button>
                  <Button type="submit" disabled={isLoading}>
                    {isLoading ? "Mengirim..." : "Kirim"}
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {/* Kanan: Gambar survey */}
        <div className="hidden lg:flex justify-center md:justify-end">
          <img src="/assets/survey.png" alt="Survey Illustration" className="w-48 h-auto" />
        </div>
      </div>
    </div>
  );
};

export default UserSurveyBox;
