"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useToast } from "./hooks/use-toast";
import { invoke } from "@tauri-apps/api/core";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { validate_password, open_website } from "./global";
import { TermsConditions } from "./terms";
import { PrivacyPolicy } from "./privacy";
import { Dialog, DialogTrigger, DialogOverlay } from "@/components/ui/dialog";

async function validate_license(license: string): Promise<boolean> {
  const isValid: boolean = await invoke("validate_license", {
    license: license,
  });

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(isValid);
    }, 1000);
  });
}

async function validate_username(username: string): Promise<boolean> {
  const isValid: boolean = await invoke("validate_username", {
    username: username,
  });

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(isValid);
    }, 1000);
  });
}

const formSchema = z.object({
  license: z
    .string()
    .refine(async (license) => await validate_license(license), {
      message: "Invalid license. Please provide a valid license key.",
    }),
  username: z
    .string()
    .min(3, {
      message: "Username must be at least 3 characters long.",
    })
    .refine(async (username) => await validate_username(username), {
      message: "Username is already in use. Please choose a different one.",
    }),
  password: z
    .string()
    .min(8, {
      message: "Password must be at least 8 characters long.",
    })
    .refine(async (password) => await validate_password(password), {
      message:
        "Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.",
    }),
  terms: z.boolean().refine((val) => val === true, {
    message: "You must accept the Terms and Conditions.",
  }),
});

const Sign_up = () => {
  const nav = useNavigate();
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: "",
      password: "",
      license: "",
      terms: false,
    },
  });
  const { toast } = useToast();

  async function onSubmit(_values: any) {
    const version: string = await invoke("get_app_version");
    toast({
      title: "Success: Signed up",
      description: `Loading Angel Panel v${version}...`,
    });

    setTimeout(() => {
      nav("/dash");
    }, 2500);
  }

  return (
    <div className="min-h-screen flex items-center justify-center login-box">
      <div className="bg-white shadow-lg p-8 rounded-lg w-full">
        <h2 className="text-2xl font-bold mb-6 text-center">
          Create an account
        </h2>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Username</FormLabel>
                  <FormControl>
                    <Input
                      type="username"
                      placeholder="Enter your desired username"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Password</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder="Enter your unique password"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="license"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>License</FormLabel>
                  <FormControl>
                    <Input
                      type="license"
                      placeholder="1E838829-5117-4AaA-8727-B15Ab178D0e5"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="flex items-center space-x-2 sign-in-meow mr-2 text-sm">
              <button
                onClick={() => nav("/sign_in")}
                className="text-black hover:bg-gray-300 hover:bg-opacity-50 px-1 rounded transition"
              >
                Sign in
              </button>
              <span className="mx-1">-</span>
              <button
                onClick={() => {
                  open_website("https://hentaihaven.xxx/");
                }}
                className="text-black hover:bg-gray-300 hover:bg-opacity-50 px-1 rounded transition"
              >
                Purchase
              </button>
            </div>
            <FormField
              control={form.control}
              name="terms"
              render={({ field }) => (
                <div className="flex items-center space-x-2 sign-in-meow mr-2 text-sm">
                  <Checkbox
                    id="terms"
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                  <label
                    htmlFor="terms"
                    className="font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    I accept the{" "}
                    <Dialog>
                      <DialogTrigger asChild>
                        <button className="text-black hover:bg-gray-300 hover:bg-opacity-50 px-1 rounded transition hover:no-underline underline">
                          Terms and Conditions
                        </button>
                      </DialogTrigger>
                      <DialogOverlay className="dialog-overlay" />
                      <TermsConditions />
                    </Dialog>{" "}
                    and acknowledge the{" "}
                    <Dialog>
                      <DialogTrigger asChild>
                        <button className="text-black hover:bg-gray-300 hover:bg-opacity-50 px-1 rounded transition hover:no-underline underline">
                          Privacy Policy
                        </button>
                      </DialogTrigger>
                      <DialogOverlay className="dialog-overlay" />
                      <PrivacyPolicy />
                    </Dialog>
                    .
                  </label>
                  <FormMessage />
                </div>
              )}
            />
            <Button type="submit" className="w-full">
              Continue
            </Button>
          </form>
        </Form>
      </div>
    </div>
  );
};

export default Sign_up;
