"use client";

import axios from "axios"
import { db } from "@/lib/db";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";

import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";


const formSchema = z.object({
  id: z.string().trim().min(12, {
    message: "Client ID should be at least 12 characters."
  }),
  secret: z.string().trim().min(12, {
    message: "Client secret should be at least 12 characters."
  })
});

export const ConnectTwitchModal = () => {
  const [isMounted, setIsMounted] = useState(false);
  const [twitchError, setTwitchError] = useState("")

  useEffect(() => {
    setIsMounted(true);
  }, []);
  
  const router = useRouter();
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      id: "",
      secret: ""
    }
  });

  const isLoading = form.formState.isSubmitting;
  
  if (!isMounted) {
    return null;
  }

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    setTwitchError("");

    try {
      const response = await axios.post("/api/settings/connections/twitch", values);
      console.log(response.data);
    } catch (error) {
      setTwitchError("Invalid client id and client secret combination.");
      console.log("[CONNECTIONS/TWITCH/POST]", error);
      return;
    }

    form.reset();
    router.refresh();
    window.location.reload();
  }

  return (
    <Dialog>
      <DialogTrigger>
        <Button>Connect Twitch</Button>
      </DialogTrigger>
      <DialogContent className="bg-white text-black p-0 overflow-hidden">
        <DialogHeader className="pt-8 px-6">
          <DialogTitle className="text-2xl text-center">Connect Your Twitch Account</DialogTitle>
          <DialogDescription className="text-center">Provide permission to access your twitch account & read chat.</DialogDescription>
        </DialogHeader>
        <div className={cn("hidden", twitchError.length > 0 && "block px-5 py-2 bg-[#FF0000] text-center items-center justify-center")}>
            {twitchError}
        </div>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-8">
            <div className="space-y-8 px-6">
              <FormField 
                control={form.control}
                name="id"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel
                    className="uppercase text-xs font-bold">
                      Client ID
                    </FormLabel>
                    <FormControl>
                      <Input
                        disabled={isLoading}
                        className="bg-white text-black"
                        placeholder="Enter your client id"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-8 px-6">
              <FormField 
                control={form.control}
                name="secret"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel
                    className="uppercase text-xs font-bold">
                      Client secret
                    </FormLabel>
                    <FormControl>
                      <Input
                        disabled={isLoading}
                        className="bg-white text-black"
                        placeholder="Enter your client secret"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <DialogFooter className="bg-gray-100 px-6 py-4">
                <Button disabled={isLoading}>Connect</Button>
              </DialogFooter>
            
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}