import { Button, Table, Text } from '@chakra-ui/react';
import { z as zod } from 'zod';

import { UserCreateWrite, ZodUserCreateWrite } from '@/back-api';
import { PageLayout } from '@/components/Layout/PageLayout';
import { ParameterLayout } from '@/components/ParameterLayout';
import { TopBar } from '@/components/TopBar/TopBar';
import { FormInput } from '@/components/form/FormInput';
import { FormPassword } from '@/components/form/FormPassword';
import { Formidable, zodResolver } from '@/components/formidable';
import { useFormidable } from '@/components/formidable/FormidableConfig';
import { UserService } from '@/service/user.service';

const options: Intl.DateTimeFormatOptions = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  //timeZoneName: "short",
};
export const ManageAccountPage = () => {
  const { data: users } = UserService.useGets();
  return (
    <>
      <TopBar title="Manage accounts" />
      <PageLayout>
        <ParameterLayout.Root>
          <ParameterLayout.HeaderBase
            title="Users"
            description="List of all users"
          />
          <ParameterLayout.Content>
            <Table.Root size="sm" variant="outline" interactive>
              <Table.Header>
                <Table.Row>
                  <Table.ColumnHeader>id</Table.ColumnHeader>
                  <Table.ColumnHeader>Login</Table.ColumnHeader>
                  <Table.ColumnHeader>e-mail</Table.ColumnHeader>
                  <Table.ColumnHeader>blocked</Table.ColumnHeader>
                  <Table.ColumnHeader>avatar</Table.ColumnHeader>
                  <Table.ColumnHeader textAlign="end">
                    Last connection
                  </Table.ColumnHeader>
                </Table.Row>
              </Table.Header>
              <Table.Body>
                {users?.map((data) => (
                  <Table.Row key={data.id}>
                    <Table.Cell>{data.id}</Table.Cell>
                    <Table.Cell>{data.login}</Table.Cell>
                    <Table.Cell>{data.email}</Table.Cell>
                    <Table.Cell>{data.blocked ? 'true' : 'false'}</Table.Cell>
                    <Table.Cell>{data.avatar ? 'yes' : 'no'}</Table.Cell>
                    <Table.Cell textAlign="end">
                      {data.lastConnection
                        ? new Date(data.lastConnection).toLocaleDateString(
                            'fr-FR',
                            options
                          )
                        : ''}
                    </Table.Cell>
                  </Table.Row>
                ))}
              </Table.Body>
            </Table.Root>
          </ParameterLayout.Content>
          <ParameterLayout.Footer />
        </ParameterLayout.Root>
        <CreateUserComponent />
      </PageLayout>
    </>
  );
};

const passwordSchema = zod
  .string()
  .min(8, 'The password must be at least 8 characters long.')
  .max(128, 'The password must not exceed 128 characters.')
  .refine((value) => /[a-z]/.test(value), {
    message: 'The password must contain at least one lowercase letter.',
  })
  .refine((value) => /[A-Z]/.test(value), {
    message: 'The password must contain at least one uppercase letter.',
  })
  .refine((value) => /\d/.test(value), {
    message: 'The password must contain at least one number.',
  })
  .refine(
    //(value) => /[]/.test(value),
    (value) => /[-_@()\{\}\[\]=+\*\/\<\>!$=\'\|`&~"#²\:\/;\.,\?]/.test(value),
    {
      message:
        'The password must contain at least one special character in: -_@(){}[]=+*/<>!$=\'|`&~"#²:/;.,?',
    }
  )
  .refine((value) => !/\s/.test(value), {
    message: 'The password must not contain spaces.',
  });

export const ZodUserCreateWithNewPassword = ZodUserCreateWrite.omit({
  password: true,
}).extend({
  password: passwordSchema,
});

export const CreateUserComponent = () => {
  const form = useFormidable<UserCreateWrite>({
    initialValues: {
      login: '',
      email: '',
      password: '',
    },
    configuration: {
      enableModifyNotification: false,
      enableReset: false,
      singleLineForm: true,
    },
    resolver: zodResolver(ZodUserCreateWithNewPassword),
  });

  //const { connect, lastError, isConnectionLoading } = useLogin();
  const userCreate = UserService.useCreate({});
  const onSubmit = () => {
    userCreate.call(form.values);
  };

  return (
    <Formidable.From form={form}>
      <ParameterLayout.Root>
        <ParameterLayout.HeaderBase
          title="Create a users"
          description="Add a new user on the server"
        />
        <ParameterLayout.Content>
          {userCreate.error && (
            <Text colorPalette="@danger">{userCreate.error.message}</Text>
          )}
          <FormInput name="login" isRequired label="Username" />
          <FormInput name="email" isRequired label="E-mail" />
          <FormPassword name="password" isRequired label="Password" />
        </ParameterLayout.Content>
        <ParameterLayout.Footer>
          <Button
            marginLeft="auto"
            marginTop="10px"
            variant="solid"
            background="green"
            width="250px"
            maxWidth="45%"
            disabled={userCreate.isCalling}
            onClick={onSubmit}
          >
            Login
          </Button>
        </ParameterLayout.Footer>
      </ParameterLayout.Root>
    </Formidable.From>
  );
};
