import z from 'zod';
import { useShallow } from 'zustand/react/shallow';
import { m } from '../../../paraglide/messages';
import { Controls } from '../../../shared/components/Controls/Controls';
import { DescriptionBlock } from '../../../shared/components/DescriptionBlock/DescriptionBlock';
import { WizardCard } from '../../../shared/components/wizard/WizardCard/WizardCard';
import { Button } from '../../../shared/defguard-ui/components/Button/Button';
import { Divider } from '../../../shared/defguard-ui/components/Divider/Divider';
import { SizedBox } from '../../../shared/defguard-ui/components/SizedBox/SizedBox';
import { ThemeSpacing } from '../../../shared/defguard-ui/types';
import { useAppForm } from '../../../shared/form';
import { formChangeLogic } from '../../../shared/formLogic';
import { Validate } from '../../../shared/validate';
import { AddLocationPageStep } from '../types';
import { useAddLocationStore } from '../useAddLocationStore';

const formSchema = z.object({
  name: z.string(m.form_error_required()).min(1, m.form_error_required()),
  endpoint: z
    .string(m.form_error_required())
    .trim()
    .min(1, m.form_error_required())
    .refine(
      (value) =>
        Validate.any(value, [
          Validate.IPv4,
          Validate.IPv6,
          Validate.Domain,
          Validate.Hostname,
        ]),
      m.form_error_invalid(),
    ),
  port: z
    .number(m.form_error_required())
    .min(1, m.form_error_min({ value: 1 }))
    .max(65535, m.form_error_port_max()),
});

type FormFields = z.infer<typeof formSchema>;

export const AddLocationStartStep = () => {
  const defaultValues = useAddLocationStore(
    useShallow(
      (s): FormFields => ({
        endpoint: s.endpoint,
        name: s.name,
        port: s.port,
      }),
    ),
  );

  const form = useAppForm({
    defaultValues,
    validationLogic: formChangeLogic,
    validators: {
      onSubmit: formSchema,
      onChange: formSchema,
    },
    onSubmit: ({ value }) => {
      useAddLocationStore.setState({
        ...value,
        activeStep: AddLocationPageStep.InternalVpnSettings,
      });
    },
  });

  return (
    <WizardCard id="add-location-start-step">
      <form
        onSubmit={(e) => {
          e.stopPropagation();
          e.preventDefault();
          form.handleSubmit();
        }}
      >
        <form.AppForm>
          <form.AppField name="name">
            {(field) => (
              <field.FormInput
                required
                label={m.profile_devices_col_location_name()}
                helper={m.profile_devices_col_location_helper()}
              />
            )}
          </form.AppField>
          <Divider spacing={ThemeSpacing.Xl2} />
          <DescriptionBlock title={m.add_location_start_public_address_title()}>
            <p>{m.add_location_start_public_address_description()}</p>
          </DescriptionBlock>
          <SizedBox height={ThemeSpacing.Lg} />
          <form.AppField name="endpoint">
            {(field) => (
              <field.FormInput
                required
                label={m.add_location_start_label_endpoint()}
                helper={m.add_location_start_helper_endpoint()}
              />
            )}
          </form.AppField>
          <SizedBox height={ThemeSpacing.Xl} />
          <form.AppField name="port">
            {(field) => (
              <field.FormInput
                required
                label={m.add_location_start_label_port()}
                helper={m.add_location_start_helper_port()}
                type="number"
              />
            )}
          </form.AppField>
          <Controls>
            <Button
              variant="outlined"
              text={m.controls_back()}
              onClick={() => {
                useAddLocationStore.setState({ isWelcome: true });
              }}
            />
            <div className="right">
              <Button
                text={m.controls_continue()}
                testId="continue"
                onClick={() => {
                  form.handleSubmit();
                }}
              />
            </div>
          </Controls>
        </form.AppForm>
      </form>
    </WizardCard>
  );
};
