import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/hooks/useAuth";
import { Navigate } from "react-router-dom";
import {
  FiUser,
  FiPhone,
  FiMapPin,
  FiCheckCircle,
  FiMail,
} from "react-icons/fi";
import { apiAccountUsersPartialUpdate } from "@/api/generated/private/account/account";
import Card from "@/components/ui/Card";
import Input from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import Spinner from "@/components/ui/Spinner";
import FormErrorBanner from "@/components/ui/FormErrorBanner";
import { applyServerErrors } from "@/utils/formErrors";

interface SettingsForm {
  first_name: string;
  last_name: string;
  phone_number: string;
  city: string;
  street: string;
  postal_code: string;
}

export default function AccountSettings() {
  const { t } = useTranslation("social");
  const { user, isAuthenticated, isLoading: authLoading, refreshUser } = useAuth();
  const [rootError, setRootError] = useState<string | undefined>();
  const [success, setSuccess] = useState(false);

  const form = useForm<SettingsForm>({
    defaultValues: {
      first_name: user?.first_name ?? "",
      last_name: user?.last_name ?? "",
      phone_number: user?.phone_number ?? "",
      city: user?.city ?? "",
      street: user?.street ?? "",
      postal_code: user?.postal_code ?? "",
    },
  });
  const { register, handleSubmit, formState, reset, clearErrors } = form;
  const { errors, isSubmitting } = formState;

  // Re-seed form once user data arrives from the auth refresh.
  useEffect(() => {
    if (user) {
      reset({
        first_name: user.first_name ?? "",
        last_name: user.last_name ?? "",
        phone_number: user.phone_number ?? "",
        city: user.city ?? "",
        street: user.street ?? "",
        postal_code: user.postal_code ?? "",
      });
    }
  }, [user, reset]);

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Spinner size={36} />
      </div>
    );
  }

  if (!isAuthenticated) {
    return <Navigate to="/social/login" replace />;
  }

  async function onSubmit(values: SettingsForm) {
    setRootError(undefined);
    setSuccess(false);
    clearErrors();
    if (!user?.id) {
      setRootError("User ID not found");
      return;
    }
    try {
      await apiAccountUsersPartialUpdate(
        user.id,
        values as Parameters<typeof apiAccountUsersPartialUpdate>[1],
      );
      await refreshUser();
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err) {
      setRootError(applyServerErrors(form, err) ?? t("accountSettings.saveError"));
    }
  }

  function onInvalid() {
    setRootError(undefined);
  }

  return (
    <div className="min-h-screen p-4">
      <div className="mx-auto max-w-3xl space-y-4">
        <Card>
          <h1 className="text-2xl font-bold text-brand-text">{t("accountSettings.title")}</h1>
          <p className="mt-1 text-sm text-brand-text/70">{t("accountSettings.appearanceLabel")}</p>
        </Card>

        <Card>
          <h2 className="mb-3 font-semibold text-brand-text">{t("accountSettings.usernameLabel")}</h2>
          <dl className="space-y-1 text-sm text-brand-text/80">
            <div className="flex gap-2"><dt className="w-32 text-brand-text/60">{t("accountSettings.usernameLabel")}</dt><dd>{user?.username}</dd></div>
            <div className="flex gap-2"><dt className="w-32 text-brand-text/60">{t("accountSettings.emailLabel")}</dt><dd className="flex items-center gap-1"><FiMail size={12} /> {user?.email}</dd></div>
            <div className="flex gap-2"><dt className="w-32 text-brand-text/60">Role</dt><dd>{user?.role || "user"}</dd></div>
          </dl>
        </Card>

        <Card>
          <form onSubmit={handleSubmit(onSubmit, onInvalid)} className="space-y-5" noValidate>
            {success && (
              <div className="flex items-center gap-2 rounded-xl border border-brand-accent/40 bg-brand-accent/10 px-4 py-3 text-sm text-brand-accent">
                <FiCheckCircle />
                {t("accountSettings.profileSaved")}
              </div>
            )}

            <FormErrorBanner message={rootError} />

            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <Input
                label={t("accountSettings.firstNameLabel")}
                icon={<FiUser />}
                placeholder={t("accountSettings.firstNamePlaceholder")}
                maxLength={150}
                autoComplete="given-name"
                disabled={isSubmitting}
                error={errors.first_name?.message}
                {...register("first_name")}
              />
              <Input
                label={t("accountSettings.lastNameLabel")}
                icon={<FiUser />}
                placeholder={t("accountSettings.lastNamePlaceholder")}
                maxLength={150}
                autoComplete="family-name"
                disabled={isSubmitting}
                error={errors.last_name?.message}
                {...register("last_name")}
              />
            </div>

            <Input
              type="tel"
              label={t("accountSettings.phoneLabel")}
              icon={<FiPhone />}
              placeholder="+420123456789"
              pattern="^\+?\d{9,15}$"
              maxLength={16}
              autoComplete="tel"
              disabled={isSubmitting}
              error={errors.phone_number?.message}
              {...register("phone_number")}
            />

            <div className="space-y-4 border-t border-brand-lines/15 pt-5">
              <h3 className="flex items-center gap-2 font-semibold text-brand-text">
                <FiMapPin /> {t("accountSettings.addressSection")}
              </h3>
              <Input
                label={t("accountSettings.cityLabel")}
                placeholder={t("accountSettings.cityPlaceholder")}
                maxLength={100}
                autoComplete="address-level2"
                disabled={isSubmitting}
                error={errors.city?.message}
                {...register("city")}
              />
              <Input
                label={t("accountSettings.streetLabel")}
                placeholder="Václavské náměstí 1"
                maxLength={200}
                autoComplete="street-address"
                disabled={isSubmitting}
                error={errors.street?.message}
                {...register("street")}
              />
              <Input
                label={t("accountSettings.postalLabel")}
                placeholder="11000"
                pattern="^\d{5}$"
                maxLength={5}
                autoComplete="postal-code"
                disabled={isSubmitting}
                error={errors.postal_code?.message}
                {...register("postal_code")}
              />
            </div>

            <Button type="submit" loading={isSubmitting} disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <Spinner size={16} /> {t("accountSettings.saving")}
                </>
              ) : (
                t("accountSettings.saveProfile")
              )}
            </Button>
          </form>
        </Card>
      </div>
    </div>
  );
}
