"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/Input";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { updateProfile } from "@/lib/actions/profile";
import { swalAlert } from "@/lib/utils/swal";

interface ProfileFormProps {
  userId: string;
  initialName: string;
  email: string;
}

export function ProfileForm({ initialName, email }: ProfileFormProps) {
  const [name, setName] = useState(initialName);
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  const initials = name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    startTransition(async () => {
      const result = await updateProfile({ name });
      if (result.success) {
        void swalAlert("Profile updated!", "Your name has been saved.", "success");
        router.refresh();
      } else {
        setError(result.error);
      }
    });
  }

  return (
    <Card className="p-6">
      <h2 className="mb-1 text-[15px] font-bold text-navy">Profile Information</h2>
      <p className="mb-5 text-[13px] text-muted">Update your display name.</p>

      {/* Avatar preview */}
      <div className="mb-5 flex items-center gap-4">
        <div className="flex h-14 w-14 items-center justify-center rounded-full bg-accent text-lg font-extrabold text-navy">
          {initials || "?"}
        </div>
        <div>
          <div className="text-[14px] font-semibold text-navy">{name || "—"}</div>
          <div className="text-[12px] text-muted">{email}</div>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="mb-1.5 block text-[12.5px] font-semibold text-navy">
            Full Name
          </label>
          <Input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Your full name"
            required
            minLength={2}
            maxLength={100}
          />
        </div>

        <div>
          <label className="mb-1.5 block text-[12.5px] font-semibold text-navy">
            Email Address
          </label>
          <Input
            value={email}
            disabled
            className="cursor-not-allowed opacity-60"
          />
          <p className="mt-1 text-[11.5px] text-muted">
            Email cannot be changed. Contact support if needed.
          </p>
        </div>

        {error && (
          <p className="rounded-[8px] bg-danger-bg px-3 py-2 text-[12.5px] text-danger">
            {error}
          </p>
        )}

        <div className="pt-1">
          <Button type="submit" loading={isPending} disabled={name.trim() === initialName}>
            Save Changes
          </Button>
        </div>
      </form>
    </Card>
  );
}
