'use client';

import type { Preloaded } from 'convex/react';
import { useMemo, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, usePreloadedQuery } from 'convex/react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';

import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Input,
  SubmitButton,
} from '@spoon/ui';

const formSchema = z.object({
  name: z
    .string()
    .trim()
    .min(5, {
      message: 'Full name is required & must be at least 5 characters.',
    })
    .max(50, {
      message: 'Full name must be less than 50 characters.',
    }),
  email: z.email({
    message: 'Please enter a valid email address.',
  }),
});

interface UserInfoFormProps {
  preloadedUser: Preloaded<typeof api.auth.getUser>;
  preloadedProvider: Preloaded<typeof api.auth.getUserProvider>;
}

export const UserInfoForm = ({
  preloadedUser,
  preloadedProvider,
}: UserInfoFormProps) => {
  const user = usePreloadedQuery(preloadedUser);
  const userProvider = usePreloadedQuery(preloadedProvider);
  const providerMap: Record<string, string> = {
    unknown: 'Provider',
    authentik: 'Authentik',
    github: 'GitHub',
  };
  const [loading, setLoading] = useState(false);

  const updateUser = useMutation(api.auth.updateUser);

  const initialValues = useMemo<z.infer<typeof formSchema>>(
    () => ({
      name: user?.name ?? '',
      email: user?.email ?? '',
    }),
    [user?.name, user?.email],
  );

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    values: initialValues,
  });

  const handleSubmit = async (values: z.infer<typeof formSchema>) => {
    if (!user) {
      toast.error('User not found.');
      return;
    }

    const name = values.name.trim();
    const email = values.email.trim().toLowerCase();
    const patch: Partial<{
      name: string;
      email: string;
    }> = {};
    if (name !== (user.name ?? '')) patch.name = name;
    if (email !== (user.email ?? '')) patch.email = email;
    if (Object.keys(patch).length === 0) {
      toast.info('No changes to save.');
      return;
    }
    setLoading(true);
    try {
      await updateUser(patch);
      form.reset(patch);
      toast.success('Profile updated successfully.');
    } catch (error) {
      console.error(error);
      toast.error('Error updating profile.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <CardHeader>
        <CardTitle>Account Information</CardTitle>
        <CardDescription>Update your name and email address</CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(handleSubmit)}
            className='space-y-4'
          >
            <FormField
              control={form.control}
              name='name'
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Full Name</FormLabel>
                  <FormControl>
                    <Input {...field} placeholder='John Doe' />
                  </FormControl>
                  <FormDescription>Your public display name</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name='email'
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      type='email'
                      placeholder='john@example.com'
                      disabled={userProvider !== 'password'}
                    />
                  </FormControl>
                  {userProvider === 'password' ? (
                    <FormDescription>
                      Your email address for account notifications
                    </FormDescription>
                  ) : (
                    <FormDescription>
                      Email is managed through your{' '}
                      {providerMap[userProvider ?? 'unknown']} account
                    </FormDescription>
                  )}
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className='flex justify-end pt-2'>
              <SubmitButton disabled={loading} pendingText='Saving...'>
                Save Changes
              </SubmitButton>
            </div>
          </form>
        </Form>
      </CardContent>
    </>
  );
};
