// Import necessary dependencies and components
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import * as z from 'zod'
import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { useState } from 'react'
import { toast } from 'sonner'
import { FiArrowRight, FiEye, FiEyeOff } from 'react-icons/fi'
import { useMutation } from '@tanstack/react-query'
import { Axios } from '@/utils/axios'
import Link from 'next/link'

// Define Zod schema for form validation
const formSchema = z
  .object({
    currentPassword: z
      .string()
      .min(8, 'Password must be at least 8 characters long.')
      .refine((value) => /[a-zA-Z]/.test(value) && /[0-9]/.test(value), {
        message: 'New Password must contain both letters and numbers.',
      }),
    newPassword: z
      .string()
      .min(8, 'New Password must be at least 8 characters long.')
      .refine((value) => /[a-zA-Z]/.test(value) && /[0-9]/.test(value), {
        message: 'New Password must contain both letters and numbers.',
      }),
    confirmPassword: z.string(),
  })
  .refine((data) => data.newPassword === data.confirmPassword, {
    message: "Passwords don't match",
    path: ['confirmPassword'],
  })

// ChangePassword component
export default function ChangePassword() {
  const [hide, setHide] = useState(false) // State for password visibility toggle
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  })

  type ChangePasswordType = z.infer<typeof formSchema> // Type for form data

  // Mutation for changing password
  const changePasswordMutation = useMutation({
    mutationKey: ['changePassword'],
    mutationFn: async (data: ChangePasswordType) => {
      return (await Axios.put(`/change-password`, { ...data })).data
    },
  })

  // Form submission handler
  const onSubmit = (data: ChangePasswordType) => {
    changePasswordMutation.mutate(data, {
      onSuccess: (result) => {
        toast('Password changed successfully.')
        form.reset() // Reset form fields
      },
      onError: (err) => {
        // @ts-ignore
        toast(err?.response.data.message)
      },
    })
  }

  return (
    <div className=" w-full h-fit flex items-center justify-center">
      <div className="w-full rounded-lg bg-surkhetSoft shadow-[0_3px_10px_rgb(0,0,0,0.2)] p-5">
        <h2 className="text-xl text-center font-semibold mb-5">
          Change Password
        </h2>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex flex-col gap-y-4 mt-7"
          >
            {/* Current Password Field */}
            <FormField
              control={form.control}
              name="currentPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Current Password</FormLabel>
                  <FormControl>
                    <Input
                      type={hide ? 'password' : 'text'}
                      placeholder="Current Password"
                      {...field}
                      className="border rounded-md p-2 focus:outline-none focus:border-blue-500"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* New Password Field */}
            <FormField
              control={form.control}
              name="newPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>New Password</FormLabel>
                  <FormControl>
                    <Input
                      type={hide ? 'password' : 'text'}
                      placeholder="New Password"
                      {...field}
                      className="border rounded-md p-2 focus:outline-none focus:border-blue-500"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Confirm Password Field */}
            <FormField
              control={form.control}
              name="confirmPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Confirm Password</FormLabel>
                  <FormControl>
                    <Input
                      type={hide ? 'password' : 'text'}
                      placeholder="Confirm Password"
                      {...field}
                      className="border rounded-md p-2 focus:outline-none focus:border-blue-500"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Toggle Password Visibility Button */}
            <Button
              type="button"
              onClick={() => setHide(!hide)}
              className="w-full bg-gray-200 text-gray-700"
            >
              {hide ? <FiEye size={21} /> : <FiEyeOff size={21} />}
              {hide ? 'Show Password' : 'Hide Password'}
            </Button>

            {/* Submit Button */}
            <Button
              type="submit"
              className="w-full bg-surkhetSoft text-white mt-2"
            >
              Change Password
            </Button>
          </form>
        </Form>
      </div>
    </div>
  )
}
