import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2, ShieldCheck } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth-store'
import { api, getApiErrorMessage } from '@/lib/api'
import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { PasswordInput } from '@/components/password-input'

const accountFormSchema = z
  .object({
    oldPassword: z.string().min(1, '请输入当前密码'),
    newPassword: z.string().min(6, '新密码至少 6 位'),
    confirmPassword: z.string().min(6, '请再次输入新密码'),
  })
  .refine((value) => value.newPassword === value.confirmPassword, {
    message: '两次输入的新密码不一致',
    path: ['confirmPassword'],
  })

type AccountFormValues = z.infer<typeof accountFormSchema>

type ChangePasswordResponse = {
  status: 'ok'
  token?: string
}

export function AccountForm() {
  const { auth } = useAuthStore()
  const form = useForm<AccountFormValues>({
    resolver: zodResolver(accountFormSchema),
    defaultValues: {
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  })

  async function onSubmit(data: AccountFormValues) {
    try {
      const response = await api.post<ChangePasswordResponse>(
        '/api/user/change-password',
        {
          oldPassword: data.oldPassword,
          newPassword: data.newPassword,
        }
      )

      if (response.data.token) {
        auth.setAccessToken(response.data.token)
      }
      if (auth.user) {
        auth.setUser({ ...auth.user, mustChangePassword: false })
      }
      form.reset()
      toast.success('密码已更新')
    } catch (error) {
      toast.error(getApiErrorMessage(error, '修改密码失败'))
    }
  }

  return (
    <div className='space-y-6'>
      {auth.user?.mustChangePassword && (
        <Alert>
          <ShieldCheck />
          <AlertTitle>请先修改默认密码</AlertTitle>
          <AlertDescription>
            当前账号需要完成密码更新后，才能继续访问其他后台页面。
          </AlertDescription>
        </Alert>
      )}

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className='max-w-md space-y-6'>
          <FormField
            control={form.control}
            name='oldPassword'
            render={({ field }) => (
              <FormItem>
                <FormLabel>当前密码</FormLabel>
                <FormControl>
                  <PasswordInput autoComplete='current-password' {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name='newPassword'
            render={({ field }) => (
              <FormItem>
                <FormLabel>新密码</FormLabel>
                <FormControl>
                  <PasswordInput autoComplete='new-password' {...field} />
                </FormControl>
                <FormDescription>
                  建议使用包含字母、数字和符号的密码。
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name='confirmPassword'
            render={({ field }) => (
              <FormItem>
                <FormLabel>确认新密码</FormLabel>
                <FormControl>
                  <PasswordInput autoComplete='new-password' {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type='submit' disabled={form.formState.isSubmitting}>
            {form.formState.isSubmitting ? (
              <Loader2 className='animate-spin' />
            ) : (
              <ShieldCheck />
            )}
            保存密码
          </Button>
        </form>
      </Form>
    </div>
  )
}
