import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router'
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
  formOptions,
  useForm,
} from '@tanstack/react-form'
import { useLogin } from '@/hooks/queries'
import { toast } from 'sonner'

interface LoginFormProps {
  username: string
  password: string
}

const defaultInput: LoginFormProps = {
  username: '',
  password: '',
}

const formOpts = formOptions({
  defaultValues: defaultInput,
})

export const Route = createFileRoute('/(auth)/login/')({
  beforeLoad: async ({ context }) => {
    const { token } = context.auth
    if (token) throw redirect({ to: '/' })
  },
  component: LoginForm,
})

function LoginForm() {
  const navigate = useNavigate()
  const loginMutation = useLogin()

  const form = useForm({
    ...formOpts,
    onSubmit: async ({ value }) => {
      try {
        await loginMutation.mutateAsync({
          username: value.username,
          password: value.password,
        })

        toast.success('Đăng nhập thành công!')
        navigate({ to: '/' })
      } catch (error: any) {
        console.error('Login error:', error)
        toast.error(
          error.response?.data?.message || 'Tài khoản hoặc mật khẩu không đúng.'
        )
      }
    },
  })

  return (
    <Card className="max-w-md mx-auto mt-20 p-6">
      <CardHeader>
        <CardTitle>Đăng nhập</CardTitle>
        <CardDescription>
          Vui lòng nhập thông tin đăng nhập của bạn.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form
          onSubmit={(e) => {
            e.preventDefault()
            form.handleSubmit()
          }}
          className="space-y-4"
        >
          {/* Username */}
          <form.Field name="username">
            {(field) => (
              <div>
                <Label htmlFor="username">Tên đăng nhập</Label>
                <Input
                  id="username"
                  value={field.state.value}
                  onChange={(e) => field.handleChange(e.target.value)}
                  placeholder="Tên đăng nhập"
                />
                {field.state.meta.isTouched && field.state.meta.errors && (
                  <p className="text-sm text-red-500 mt-1">
                    {field.state.meta.errors}
                  </p>
                )}
              </div>
            )}
          </form.Field>

          {/* Password */}
          <form.Field name="password">
            {(field) => (
              <div>
                <Label htmlFor="password">Mật khẩu</Label>
                <Input
                  id="password"
                  type="password"
                  value={field.state.value}
                  onChange={(e) => field.handleChange(e.target.value)}
                  placeholder="Mật khẩu"
                />
                {field.state.meta.isTouched && field.state.meta.errors && (
                  <p className="text-sm text-red-500 mt-1">
                    {field.state.meta.errors}
                  </p>
                )}
              </div>
            )}
          </form.Field>

          <Button type="submit" className="w-full" disabled={loginMutation.isPending}>
            {loginMutation.isPending ? 'Đang đăng nhập...' : 'Đăng nhập'}
          </Button>
        </form>
      </CardContent>
      <CardFooter>
        <p className="text-sm text-muted-foreground">
          Chưa có tài khoản? <span className="underline cursor-pointer">Đăng ký</span>
        </p>
      </CardFooter>
    </Card>
  )
}
