"use client";

import { FormEvent, useState, useEffect } from "react";
import { PageHeader } from "@/components/ui/PageHeader";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { AlertMessage } from "@/components/settings/banks/AlertMessage";
import { BREADCRUMBS } from "@/constants/breadcrumbs";
import { SETTINGS_PAGE_CONTAINER } from "../constants";
import { validateRequired } from "@/lib/common";
import { clearFieldError } from "@/utils/form-validation";
import { User, Loader2 } from "lucide-react";

interface SessionUser {
  user_id: number;
  email: string;
  full_name?: string;
  first_name?: string;
  last_name?: string;
}

type FieldKey = "first_name" | "last_name";

export default function ProfileSettingsPage() {
  const [user, setUser] = useState<SessionUser | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<FieldKey, string>>>({});
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveSuccess, setSaveSuccess] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function fetchUser() {
      try {
        const res = await fetch("/api/session/status", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify({}),
        });
        const data = await res.json().catch(() => null);

        if (cancelled) return;
        if (!res.ok || !data?.authenticated) {
          setLoadError(data?.error ?? "Failed to load profile.");
          return;
        }

        const u = data.user as SessionUser | undefined;
        if (u) {
          setUser(u);
          setFirstName(u.first_name ?? "");
          setLastName(u.last_name ?? "");
        } else {
          setLoadError("No user data returned.");
        }
      } catch {
        if (!cancelled) setLoadError("Failed to load profile.");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    fetchUser();
    return () => {
      cancelled = true;
    };
  }, []);

  const clearError = (field: FieldKey) => {
    setFieldErrors((prev) => clearFieldError(prev, field));
  };

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaveError(null);
    setSaveSuccess(null);

    const errors: Partial<Record<FieldKey, string>> = {};
    const firstError = validateRequired(firstName.trim(), "First name");
    if (firstError) errors.first_name = firstError;
    const lastError = validateRequired(lastName.trim(), "Last name");
    if (lastError) errors.last_name = lastError;

    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }

    setFieldErrors({});
    setSaving(true);

    try {
      const res = await fetch("/api/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          first_name: firstName.trim(),
          last_name: lastName.trim(),
          full_name: [firstName.trim(), lastName.trim()].filter(Boolean).join(" ").trim() || undefined,
        }),
      });

      const data = await res.json().catch(() => ({}));

      if (!res.ok) {
        setSaveError((data as { error?: string }).error ?? "Failed to update profile. Please try again.");
        return;
      }

      setSaveSuccess("Profile updated successfully.");
      setUser((prev) =>
        prev
          ? {
              ...prev,
              first_name: firstName.trim(),
              last_name: lastName.trim(),
              full_name: [firstName.trim(), lastName.trim()].filter(Boolean).join(" ").trim() || prev.full_name,
            }
          : null
      );
    } catch {
      setSaveError("Network error. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <div className={SETTINGS_PAGE_CONTAINER}>
        <PageHeader
          title="My Profile"
          description="View and edit your profile information."
          breadcrumbs={[...BREADCRUMBS.profileSettings]}
        />
        <div className="mt-6 flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-slate-400" aria-hidden />
        </div>
      </div>
    );
  }

  if (loadError || !user) {
    return (
      <div className={SETTINGS_PAGE_CONTAINER}>
        <PageHeader
          title="My Profile"
          description="View and edit your profile information."
          breadcrumbs={[...BREADCRUMBS.profileSettings]}
        />
        <div className="mt-6 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
          {loadError ?? "User not found."}
        </div>
      </div>
    );
  }

  const displayName =
    user.full_name ||
    [user.first_name, user.last_name].filter(Boolean).join(" ") ||
    "—";

  return (
    <div className={SETTINGS_PAGE_CONTAINER}>
      <PageHeader
        title="My Profile"
        description="View and edit your profile information."
        breadcrumbs={[...BREADCRUMBS.profileSettings]}
      />

      <AlertMessage error={saveError} success={saveSuccess} />

      <div className="mt-6 max-w-xl space-y-6">
        <section className="rounded-lg border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="text-base font-semibold text-slate-800 flex items-center gap-2">
            <User className="h-4 w-4" />
            Profile information
          </h2>
          <p className="mt-1 text-sm text-slate-500">
            Update your name. Your email is managed by your account and cannot be changed here.
          </p>

          <form onSubmit={handleSubmit} className="mt-6">
            <FieldGroup>
              <Field>
                <FieldLabel htmlFor="profile-email">Email</FieldLabel>
                <Input
                  id="profile-email"
                  type="email"
                  value={user.email ?? ""}
                  readOnly
                  disabled
                  className="bg-slate-50 text-slate-600"
                  aria-describedby="profile-email-hint"
                />
                <p id="profile-email-hint" className="text-muted-foreground text-xs mt-1">
                  Contact your administrator to change your email.
                </p>
              </Field>

              <Field>
                <FieldLabel htmlFor="profile-first-name">First name</FieldLabel>
                <Input
                  id="profile-first-name"
                  type="text"
                  value={firstName}
                  onChange={(e) => {
                    setFirstName(e.target.value);
                    clearError("first_name");
                  }}
                  placeholder="First name"
                  autoComplete="given-name"
                  aria-invalid={!!fieldErrors.first_name}
                />
                {fieldErrors.first_name && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.first_name}
                  </p>
                )}
              </Field>

              <Field>
                <FieldLabel htmlFor="profile-last-name">Last name</FieldLabel>
                <Input
                  id="profile-last-name"
                  type="text"
                  value={lastName}
                  onChange={(e) => {
                    setLastName(e.target.value);
                    clearError("last_name");
                  }}
                  placeholder="Last name"
                  autoComplete="family-name"
                  aria-invalid={!!fieldErrors.last_name}
                />
                {fieldErrors.last_name && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.last_name}
                  </p>
                )}
              </Field>

              <Field>
                <FieldLabel>Display name</FieldLabel>
                <p className="text-sm text-slate-600 py-2">{displayName}</p>
                <p className="text-muted-foreground text-xs">
                  Shown across the app. Updated when you save first and last name.
                </p>
              </Field>

              <div className="pt-2">
                <Button type="submit" disabled={saving}>
                  {saving ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Saving…
                    </>
                  ) : (
                    "Save profile"
                  )}
                </Button>
              </div>
            </FieldGroup>
          </form>
        </section>
      </div>
    </div>
  );
}
