"use client";

import { useUserProfile } from "@/hooks/useUserProfile";

export default function DashboardSettings() {
  const { profile, user, updateProfile, changePassword, resendVerification, saving, error, success, clearMessages } = useUserProfile();

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    clearMessages();
    const fd = new FormData(e.currentTarget);
    await updateProfile({
      name: fd.get("name") as string,
      company: fd.get("company") as string,
      department: fd.get("department") as string,
      jobLevel: fd.get("jobLevel") as string,
      gender: fd.get("gender") as string,
      age: parseInt(fd.get("age") as string) || undefined,
    });
  }

  async function handlePassword(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    clearMessages();
    const fd = new FormData(e.currentTarget);
    const current = fd.get("currentPassword") as string;
    const baru = fd.get("newPassword") as string;
    if (baru.length < 6) return;
    await changePassword(current, baru);
    (e.target as HTMLFormElement).reset();
  }

  async function handleResend() {
    clearMessages();
    await resendVerification();
  }

  return (
    <div className="mx-auto max-w-2xl space-y-8">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Pengaturan Akun</h1>
        <p className="mt-1 text-sm text-ink-soft">Kelola data profil dan keamanan kamu.</p>
      </div>

      {success && <p className="rounded-lg bg-success/10 px-4 py-3 text-sm font-medium text-success">{success}</p>}
      {error && <p className="rounded-lg bg-danger/10 px-4 py-3 text-sm font-medium text-danger">{error}</p>}

      <form
        key={profile ? profile.uid : "loading"}
        onSubmit={handleSubmit}
        className="rounded-2xl border border-border bg-surface p-8 space-y-6"
      >
        <h2 className="font-display text-lg font-semibold text-ink">Informasi Pribadi</h2>
        <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
          <Field name="name" label="Nama Lengkap" defaultValue={profile?.name || ""} />
          <Field name="email" label="Email" defaultValue={user?.email || ""} disabled />
          <Field name="company" label="Perusahaan" defaultValue={profile?.company || ""} />
          <Field name="department" label="Department" defaultValue={profile?.department || ""} />
          <Field name="jobLevel" label="Job Level" defaultValue={profile?.jobLevel || ""} />
          <Field name="gender" label="Gender" defaultValue={profile?.gender || ""} />
          <Field name="age" label="Usia" type="number" defaultValue={profile?.age?.toString() || ""} />
        </div>
        {user && !user.emailVerified && (
          <div className="flex items-center gap-3 rounded-lg bg-warning/10 px-4 py-3">
            <p className="text-sm text-ink-soft">Email belum diverifikasi.</p>
            <button type="button" onClick={handleResend} className="text-sm font-medium text-primary hover:underline">Kirim ulang</button>
          </div>
        )}
        <button type="submit" disabled={saving} className="w-full rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary-soft disabled:opacity-50">
          {saving ? "Menyimpan..." : "Simpan Perubahan"}
        </button>
      </form>

      {user?.providerData?.some((p) => p?.providerId === "password") && (
        <form onSubmit={handlePassword} className="rounded-2xl border border-border bg-surface p-8 space-y-6">
          <h2 className="font-display text-lg font-semibold text-ink">Ubah Password</h2>
          <Field name="currentPassword" label="Password Saat Ini" type="password" />
          <Field name="newPassword" label="Password Baru" type="password" placeholder="Minimal 6 karakter" />
          <button type="submit" disabled={saving} className="w-full rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary-soft disabled:opacity-50">
            {saving ? "Menyimpan..." : "Ubah Password"}
          </button>
        </form>
      )}
    </div>
  );
}

function Field({ label, name, type = "text", placeholder, defaultValue, disabled }: { label: string; name: string; type?: string; placeholder?: string; defaultValue?: string; disabled?: boolean }) {
  return (
    <div>
      <label htmlFor={name} className="mb-1.5 block text-sm font-medium text-ink">{label}</label>
      <input
        id={name}
        name={name}
        type={type}
        defaultValue={defaultValue}
        disabled={disabled}
        placeholder={placeholder}
        className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary disabled:opacity-50"
      />
    </div>
  );
}
