'use client';
import { emailLoginFormSchema } from '@repo/shared/lib/schemas/auth';
import { BetterAuth } from '@repo/shared/services/auth-client';
import { useForm } from '@tanstack/react-form';
import { Button } from '@workspace/ui/components/button';
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
} from '@workspace/ui/components/card';
import { Input } from '@workspace/ui/components/input';
import { Label } from '@workspace/ui/components/label';
import { Separator } from '@workspace/ui/components/separator';
import { Flex, Grid } from '@workspace/ui/design-system/spacing';
import Spinner from '@workspace/ui/design-system/spinner';
import {
  H3,
  LinkCode,
  Muted,
  Small,
  XSmall,
} from '@workspace/ui/design-system/typography';
import FormMessage from '@workspace/ui/global/form/form-message';
import { Effect } from 'effect';
import { standardSchemaV1 } from 'effect/Schema';
import { ChevronsRight } from 'lucide-react';
import Link from 'next/link';
import { webRuntime } from '@/runtimes/web-runtime';

type AuthFormModes = 'sign-in' | 'sign-up';

const program = Effect.gen(function* () {
  const betterAuth = yield* BetterAuth;
  const authClient = yield* betterAuth.getClient;

  return { authClient };
});

const AuthForm = <TFormMode extends AuthFormModes>({
  mode,
}: {
  mode: TFormMode;
}) => {
  const programData = webRuntime.runSync(program);

  const form = useForm({
    defaultValues: {
      email: '',
      password: '',
    },
    validators: {
      onSubmit: standardSchemaV1(emailLoginFormSchema),
    },
    onSubmit: async (values) => {},
  });

  return (
    <Card className="max-w-md">
      <CardHeader>
        <Flex
          align="center"
          className="text-center"
          direction="col"
          justify="center"
          spacing="xs"
          wrap="nowrap"
        >
          <H3>{mode === 'sign-in' ? 'Welcome Back' : 'Create Your Account'}</H3>
          <Muted className="text-balance">
            {mode === 'sign-in'
              ? 'Sign in to your CCE Connect account to continue'
              : 'Join CCE Connect and start your journey with us today'}
          </Muted>
        </Flex>
      </CardHeader>
      <CardContent>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            form.handleSubmit();
          }}
        >
          <Flex
            align="center"
            direction="col"
            justify="center"
            spacing="lg"
            wrap="nowrap"
          >
            <Grid className="w-full" cols={1} spacing="md">
              <Flex
                align="start"
                direction="col"
                justify="center"
                spacing="sm"
                wrap="nowrap"
              >
                <Label htmlFor="email">Email Address</Label>
                <form.Field name="email">
                  {(field) => (
                    <>
                      <Input
                        id="email"
                        name={field.name}
                        onBlur={field.handleBlur}
                        onChange={(e) => field.handleChange(e.target.value)}
                        placeholder="Enter your email address"
                        value={field.state.value}
                      />
                      <FormMessage field={field} />
                    </>
                  )}
                </form.Field>
              </Flex>

              <Flex
                align="start"
                direction="col"
                justify="center"
                spacing="sm"
                wrap="nowrap"
              >
                <Flex
                  align="center"
                  className="w-full"
                  direction="row"
                  justify="between"
                  spacing="lg"
                  wrap="nowrap"
                >
                  <Label htmlFor="password">Password</Label>
                  {mode === 'sign-in' && (
                    <Link href="/forgot-password">
                      <Muted>
                        <XSmall>
                          <LinkCode>Forgot your password?</LinkCode>
                        </XSmall>
                      </Muted>
                    </Link>
                  )}
                </Flex>
                <form.Field name="password">
                  {(field) => (
                    <>
                      <Input
                        id="password"
                        name={field.name}
                        onBlur={field.handleBlur}
                        onChange={(e) => field.handleChange(e.target.value)}
                        placeholder={
                          mode === 'sign-in'
                            ? 'Enter your password'
                            : 'Create a strong password'
                        }
                        type="password"
                        value={field.state.value}
                      />
                      <FormMessage field={field} />
                    </>
                  )}
                </form.Field>
              </Flex>

              <form.Subscribe
                selector={(state) => [state.canSubmit, state.isSubmitting]}
              >
                {([canSubmit, isSubmitting]) => (
                  <Button
                    disabled={!canSubmit || isSubmitting}
                    type="submit"
                    variant="default"
                  >
                    {mode === 'sign-in' ? 'Sign In' : 'Create Account'}
                    {isSubmitting ? (
                      <Spinner />
                    ) : (
                      <ChevronsRight className="size-4" />
                    )}
                  </Button>
                )}
              </form.Subscribe>
            </Grid>

            <Flex
              align="center"
              direction="row"
              justify="center"
              spacing="sm"
              wrap="nowrap"
            >
              <Separator />
              <Muted className="whitespace-nowrap">
                <XSmall>
                  {mode === 'sign-in' ? 'Or sign in with' : 'Or sign up with'}
                </XSmall>
              </Muted>
              <Separator />
            </Flex>

            <Grid cols={3} spacing="sm">
              <Button className="w-full" type="button" variant="outline">
                Google
              </Button>
              <Button className="w-full" type="button" variant="outline">
                Facebook
              </Button>
              <Button className="w-full" type="button" variant="outline">
                Passkey
              </Button>
            </Grid>
          </Flex>
        </form>
      </CardContent>
      <CardFooter>
        <Flex
          align="center"
          className="w-full"
          direction="row"
          justify="center"
          spacing="sm"
          wrap="nowrap"
        >
          <Small>
            {mode === 'sign-in'
              ? "Don't have an account?"
              : 'Already have an account?'}{' '}
            <Link
              className="inline"
              href={mode === 'sign-in' ? '/sign-up' : '/sign-in'}
            >
              <Muted>
                <LinkCode>
                  {mode === 'sign-in' ? 'Create one here' : 'Sign in here'}
                </LinkCode>
              </Muted>
            </Link>
          </Small>
        </Flex>
      </CardFooter>
    </Card>
  );
};

export default AuthForm;
