"use client";

import Link from "next/link";
import { useEffect, useState, type FormEvent } from "react";
import { JalaliDatePicker } from "@/components/jalali-date-picker/jalali-date-picker";
import {
  getBirthdayMinYear,
  getTodayGregorianIso,
} from "@/components/jalali-date-picker/utils";
import { Select } from "@/components/select";
import { ProfileHeader } from "@/features/profile/components/profile-header";
import { ProfileAvatar } from "@/features/profile/components/profile-avatar";
import { PushNotificationsSettings } from "@/features/push/components/push-notifications-settings";
import { getSubscriptionVisual } from "@/features/profile/utils/subscription-theme";
import { profileDict } from "@/features/profile/dict";
import {
  DEFAULT_PROFILE_TIMEZONE,
  profileTimezoneOptions,
} from "@/features/profile/constants/timezones";
import {
  useProfile,
  useUpdateProfileMutation,
} from "@/features/profile/hooks/use-profile";
import type { ProfileFormValues, UserGender } from "@/features/profile/types";
import { panelDict } from "@/features/panel/dict";
import { useLogout } from "@/features/auth/hooks/use-login";

const genderOptions: UserGender[] = ["MALE", "FEMALE"];

const emptyValues: ProfileFormValues = {
  gender: "",
  birthday: "",
  timezone: DEFAULT_PROFILE_TIMEZONE,
  currentPassword: "",
  password: "",
};

function toIsoDate(value: string | null | undefined) {
  if (!value) return "";
  return value.slice(0, 10);
}

function validateForm(
  values: ProfileFormValues,
  hasPassword: boolean,
): Partial<Record<keyof ProfileFormValues, string>> {
  const errors: Partial<Record<keyof ProfileFormValues, string>> = {};

  if (values.password) {
    if (values.password.length < 8) {
      errors.password = profileDict.passwordTooShort;
    }

    if (hasPassword && !values.currentPassword.trim()) {
      errors.currentPassword = profileDict.currentPasswordRequired;
    }
  }

  return errors;
}

export function ProfilePageContent() {
  const { data: profile, isLoading } = useProfile();
  const updateProfileMutation = useUpdateProfileMutation();
  const logout = useLogout();
  const [values, setValues] = useState<ProfileFormValues>(emptyValues);
  const [errors, setErrors] = useState<
    Partial<Record<keyof ProfileFormValues, string>>
  >({});

  useEffect(() => {
    if (!profile) return;

    setValues({
      gender: profile.gender ?? "",
      birthday: toIsoDate(profile.birthday),
      timezone: profile.timezone || DEFAULT_PROFILE_TIMEZONE,
      currentPassword: "",
      password: "",
    });
    setErrors({});
  }, [profile]);

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!profile) return;

    const nextErrors = validateForm(values, profile.hasPassword);
    setErrors(nextErrors);

    if (Object.keys(nextErrors).length > 0) {
      return;
    }

    const payload: {
      gender?: UserGender;
      birthday?: string;
      timezone?: string;
      password?: string;
      currentPassword?: string;
    } = {};

    if (values.gender) {
      payload.gender = values.gender;
    }

    payload.birthday = values.birthday || undefined;
    payload.timezone = values.timezone || DEFAULT_PROFILE_TIMEZONE;

    if (values.password) {
      payload.password = values.password;

      if (profile.hasPassword) {
        payload.currentPassword = values.currentPassword;
      }
    }

    updateProfileMutation.mutate(payload, {
      onSuccess: () => {
        setValues((current) => ({
          ...current,
          currentPassword: "",
          password: "",
        }));
      },
    });
  };

  const inputClassName =
    "h-12 w-full rounded-2xl border-0 bg-input px-4 text-sm text-foreground shadow-soft-sm outline-none ring-1 ring-border transition-shadow placeholder:text-muted-foreground focus:ring-2 focus:ring-primary disabled:cursor-not-allowed disabled:opacity-60";

  if (isLoading) {
    return (
      <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-4 px-4 py-4 sm:gap-5 sm:px-6 sm:py-6">
        <ProfileHeader />
        <p className="px-1 text-sm text-muted-foreground">{panelDict.loading}</p>
      </div>
    );
  }

  if (!profile) {
    return null;
  }

  return (
    <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-4 px-4 py-4 sm:gap-5 sm:px-6 sm:py-6">
      <ProfileHeader />

      <div className="flex flex-col items-center gap-2 px-1">
        <ProfileAvatar subscription={profile.subscription} size="lg" />
        <p className="text-center text-xs text-muted-foreground">
          {getSubscriptionVisual(profile.subscription).tooltip}
        </p>
      </div>

      <form
        onSubmit={handleSubmit}
        className="flex flex-col gap-5 rounded-3xl bg-card p-5 shadow-soft-sm sm:p-6"
        noValidate
      >
        {profile.phoneNumber ? (
          <div className="space-y-2">
            <label className="block text-sm font-medium text-card-foreground">
              {profileDict.phoneNumber}
            </label>
            <input
              type="text"
              readOnly
              dir="ltr"
              value={profile.phoneNumber}
              className={`${inputClassName} text-start`}
            />
          </div>
        ) : null}

        {profile.email ? (
          <div className="space-y-2">
            <label className="block text-sm font-medium text-card-foreground">
              {profileDict.email}
            </label>
            <input
              type="email"
              readOnly
              dir="ltr"
              value={profile.email}
              className={`${inputClassName} text-start`}
            />
          </div>
        ) : null}

        <div className="space-y-2">
          <label
            htmlFor="gender"
            className="block text-sm font-medium text-card-foreground"
          >
            {profileDict.gender}
          </label>
          <Select
            id="gender"
            value={values.gender}
            onChange={(event) => {
              const gender = event.target.value as UserGender | "";
              setValues((current) => ({ ...current, gender }));
            }}
          >
            <option value="">{profileDict.genderPlaceholder}</option>
            {genderOptions.map((option) => (
              <option key={option} value={option}>
                {profileDict.genders[option]}
              </option>
            ))}
          </Select>
        </div>

        <div className="space-y-2">
          <label className="block text-sm font-medium text-card-foreground">
            {profileDict.birthday}
          </label>
          <JalaliDatePicker
            value={values.birthday}
            maxDate={getTodayGregorianIso()}
            minYear={getBirthdayMinYear()}
            onChange={(birthday) =>
              setValues((current) => ({ ...current, birthday }))
            }
          />
        </div>

        <div className="space-y-2">
          <label
            htmlFor="timezone"
            className="block text-sm font-medium text-card-foreground"
          >
            {profileDict.timezone}
          </label>
          <Select
            id="timezone"
            value={values.timezone}
            onChange={(event) => {
              setValues((current) => ({
                ...current,
                timezone: event.target.value,
              }));
            }}
          >
            {profileTimezoneOptions.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </Select>
          <p className="text-xs text-muted-foreground">{profileDict.timezoneHint}</p>
        </div>

        <div className="space-y-4 border-t border-border pt-4">
          <p className="text-sm font-semibold text-card-foreground">
            {profileDict.passwordSection}
          </p>

          {profile.hasPassword ? (
            <div className="space-y-2">
              <label
                htmlFor="currentPassword"
                className="block text-sm font-medium text-card-foreground"
              >
                {profileDict.currentPassword}
              </label>
              <input
                id="currentPassword"
                type="password"
                autoComplete="current-password"
                dir="ltr"
                value={values.currentPassword}
                onChange={(event) => {
                  setValues((current) => ({
                    ...current,
                    currentPassword: event.target.value,
                  }));

                  if (errors.currentPassword) {
                    setErrors((current) => ({
                      ...current,
                      currentPassword: undefined,
                    }));
                  }
                }}
                placeholder={profileDict.currentPasswordPlaceholder}
                className={`${inputClassName} text-start`}
              />
              {errors.currentPassword ? (
                <p className="text-sm text-destructive">
                  {errors.currentPassword}
                </p>
              ) : null}
            </div>
          ) : null}

          <div className="space-y-2">
            <label
              htmlFor="password"
              className="block text-sm font-medium text-card-foreground"
            >
              {profile.hasPassword
                ? profileDict.newPassword
                : profileDict.setPassword}
            </label>
            <input
              id="password"
              type="password"
              autoComplete="new-password"
              dir="ltr"
              value={values.password}
              onChange={(event) => {
                setValues((current) => ({
                  ...current,
                  password: event.target.value,
                }));

                if (errors.password) {
                  setErrors((current) => ({
                    ...current,
                    password: undefined,
                  }));
                }
              }}
              placeholder={profileDict.newPasswordPlaceholder}
              className={`${inputClassName} text-start`}
            />
            {errors.password ? (
              <p className="text-sm text-destructive">{errors.password}</p>
            ) : null}
          </div>
        </div>

        <button
          type="submit"
          disabled={updateProfileMutation.isPending}
          className="inline-flex h-12 items-center justify-center rounded-2xl bg-primary px-6 text-sm font-semibold text-primary-foreground shadow-soft-sm transition-all hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-70"
        >
          {updateProfileMutation.isPending
            ? profileDict.saving
            : profileDict.save}
        </button>
      </form>

      <PushNotificationsSettings />

      <div className="flex flex-col gap-3">
        <Link
          href="/panel/subscription"
          className="inline-flex h-12 items-center justify-center rounded-2xl border border-primary/30 bg-primary/5 px-6 text-sm font-semibold text-primary shadow-soft-sm transition-colors hover:bg-primary/10"
        >
          {profileDict.manageSubscription}
        </Link>
        <Link
          href="/panel/support"
          className="inline-flex h-12 items-center justify-center rounded-2xl border border-border bg-card px-6 text-sm font-semibold text-foreground shadow-soft-sm transition-colors hover:bg-muted"
        >
          {profileDict.support}
        </Link>
      </div>

      <button
        type="button"
        onClick={logout}
        className="inline-flex h-12 items-center justify-center rounded-2xl border border-destructive/30 bg-card px-6 text-sm font-semibold text-destructive shadow-soft-sm transition-colors hover:bg-destructive/10"
      >
        {profileDict.logout}
      </button>
    </div>
  );
}
