/* eslint-disable @next/next/no-img-element */
"use client";

import { UserInfo } from "@/ldap";
import React from "react";
import styles from "./AboutMe.module.css";
import AvatarChanger from "@/components/AvatarChanger";
import Input, { Hint, Label } from "@/components/Input";
import { Form, Formik, FormikHelpers } from "formik";
import PrettyForm from "@/components/PrettyForm";
import Toast from "@/components/Toast";
import { AuthProviderState } from "@/auth/AuthProvider";
import Connection from "@/components/Connection";
import DiscordIcon from "@/components/icons/DiscordIcon";
import GitHubIcon from "@/components/icons/GitHubIcon";
import TailscaleIcon from "@/components/icons/TailscaleIcon";
import MigaduIcon from "@/components/icons/MigaduIcon";
import { AboutMeSchema, aboutMeSchema } from "@/schemas";
import update from "@/actions/update";
import { toFormikValidationSchema } from "zod-formik-adapter";

export default function AboutMe({
  info,
  providers: [discordState, githubState]
}: {
  info: UserInfo;
  providers: AuthProviderState[];
}) {
  // TODO: Reimplement password changing.
  const [globalError, setGlobalError] = React.useState<string | null>(null);
  const [madeProfileChanges, setMadeChanges] = React.useState(false);
  const [madePasswordChanges, setMadePasswordChanges] = React.useState(false);

  const initialValues: AboutMeSchema = {
    username: info.username,
    displayName: info.displayName,
    email: info.email,
    avatar: info.avatar
  };

  async function handleFormSubmit(
    data: AboutMeSchema,
    { setSubmitting }: FormikHelpers<AboutMeSchema>
  ) {
    setMadeChanges(false);
    setSubmitting(true);
    const res = await update(data);
    setSubmitting(false);

    if (res.ok) {
      setMadeChanges(true);
    } else {
      if (res.error != undefined) {
        setGlobalError("Unknown error: " + res.error);
      }
    }
  }

  return (
    <div className={styles.content}>
      <PrettyForm globalError={globalError}>
        <Formik
          initialValues={initialValues}
          onSubmit={handleFormSubmit}
          validationSchema={toFormikValidationSchema(aboutMeSchema)}
        >
          {({ isSubmitting }) => (
            <Form className={styles.profileGrid}>
              <div className={styles.profileTower}>
                <Input
                  type="file"
                  name="avatar"
                  customRender={(fieldProps) => (
                    <AvatarChanger
                      currentAvatarBlob={fieldProps.field.value}
                      onChange={(newBlob) =>
                        fieldProps.form.setFieldValue("avatar", newBlob)
                      }
                      vertical
                    />
                  )}
                />
              </div>

              <div>
                <h2 className={styles.userName}>{info.username}</h2>
                <div className={styles.rightGrid}>
                  <div className={styles.profile}>
                    {madeProfileChanges ? (
                      <Toast>Saved your changes.</Toast>
                    ) : null}
                    <Input
                      type="text"
                      name="username"
                      label="Username"
                      defaultValue={info.username}
                      disabled
                      hint="This can&rsquo;t be changed."
                    />
                    <Input
                      type="text"
                      name="displayName"
                      label="Display name"
                      defaultValue={info.displayName}
                    />
                    <Input
                      type="email"
                      name="email"
                      label="Email"
                      defaultValue={info.email}
                    />

                    <hr className={styles.spacer} />

                    <input
                      type="submit"
                      value="Save"
                      className={styles.fancyInput}
                      disabled={isSubmitting}
                    />

                    <div className={styles.multiButtons}>
                      <button type="button">Change password</button>

                      <button
                        type="button"
                        onClick={async () => {
                          document.cookie =
                            "ticket=; expires=" +
                            new Date().toUTCString() +
                            "; path=/";
                          window.location.href = "/";
                        }}
                      >
                        Log out
                      </button>
                    </div>
                  </div>

                  <div className={styles.connections}>
                    <Label>Connections</Label>
                    <Hint>Click to link, hold to unlink.</Hint>

                    <Connection
                      service="Discord"
                      authState={discordState}
                      icon={DiscordIcon}
                    />
                    <Connection
                      service="GitHub"
                      authState={githubState}
                      icon={GitHubIcon}
                    />
                    <Connection
                      service="Tailscale"
                      icon={TailscaleIcon}
                      unavailable
                    />
                    <Connection
                      service="Migadu"
                      icon={MigaduIcon}
                      unavailable
                    />
                  </div>
                </div>
              </div>
            </Form>
          )}
        </Formik>
      </PrettyForm>
    </div>
  );
}
