"use client";

import { useActionState, useRef, useState, type ChangeEvent } from "react";
import Image from "next/image";
import {
  AlertCircle,
  Camera,
  CheckCircle2,
  Loader2,
  User as UserIcon,
  Trash2,
} from "lucide-react";
import { updateProfile, type ProfileFormState } from "./actions";
import { COUNTRIES } from "@/lib/membership/countries";
import { PROFESSIONAL_ROLES } from "@/lib/membership/application-schema";
import { Button } from "@/components/Button";

const initial: ProfileFormState = { ok: false };

type Props = {
  name: string;
  country: string;
  institution: string;
  professionalRole: string;
  bio: string;
  specialty: string;
  yearsExperience: number | null;
  orcidUrl: string | null;
  linkedinUrl: string | null;
  websiteUrl: string | null;
  twitterUrl: string | null;
  avatarPath: string | null;
  visibleInDirectory: boolean;
};

export function ProfileForm(props: Props) {
  const [state, action, pending] = useActionState(updateProfile, initial);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(
    props.avatarPath,
  );
  const [removeAvatar, setRemoveAvatar] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  function handleAvatarChange(e: ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 6 * 1024 * 1024) {
      window.alert("Image must be under 6 MB.");
      if (fileInputRef.current) fileInputRef.current.value = "";
      return;
    }
    setRemoveAvatar(false);
    const reader = new FileReader();
    reader.onload = () => setAvatarPreview(reader.result as string);
    reader.readAsDataURL(file);
  }

  function handleRemoveAvatar() {
    setRemoveAvatar(true);
    setAvatarPreview(null);
    if (fileInputRef.current) fileInputRef.current.value = "";
  }

  return (
    <form action={action} className="space-y-6">
      {state.message && (
        <div
          role="alert"
          className={
            state.ok
              ? "flex items-start gap-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-900"
              : "flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800"
          }
        >
          {state.ok ? (
            <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
          ) : (
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
          )}
          <span>{state.message}</span>
        </div>
      )}

      {/* Avatar */}
      <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
        <h3 className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
          Profile photo
        </h3>
        <div className="mt-4 flex items-center gap-5">
          <div className="relative h-24 w-24 overflow-hidden rounded-full border border-[var(--color-line)] bg-[var(--color-mist)]">
            {avatarPreview ? (
              avatarPreview.startsWith("data:") ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={avatarPreview}
                  alt=""
                  className="h-full w-full object-cover"
                />
              ) : (
                <Image
                  src={avatarPreview}
                  alt=""
                  width={96}
                  height={96}
                  className="h-full w-full object-cover"
                />
              )
            ) : (
              <div className="flex h-full w-full items-center justify-center text-[var(--color-slate)]">
                <UserIcon className="h-10 w-10" aria-hidden />
              </div>
            )}
          </div>
          <div className="flex flex-col gap-2">
            <input
              ref={fileInputRef}
              type="file"
              name="avatar"
              accept="image/jpeg,image/png,image/webp,image/gif"
              onChange={handleAvatarChange}
              className="hidden"
              id="avatar-input"
            />
            <label
              htmlFor="avatar-input"
              className="inline-flex cursor-pointer items-center gap-1.5 self-start rounded-lg border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
            >
              <Camera className="h-3.5 w-3.5" aria-hidden />
              {avatarPreview ? "Change photo" : "Upload photo"}
            </label>
            {avatarPreview && (
              <button
                type="button"
                onClick={handleRemoveAvatar}
                className="inline-flex items-center gap-1.5 self-start rounded-lg border border-red-200 bg-white px-3 py-1.5 text-[13px] font-semibold text-red-700 hover:bg-red-50"
              >
                <Trash2 className="h-3.5 w-3.5" aria-hidden />
                Remove
              </button>
            )}
            <span className="text-[11px] text-[var(--color-slate)]">
              JPG/PNG/WEBP · max 6 MB. Cropped to 512×512.
            </span>
          </div>
        </div>
        {removeAvatar && <input type="hidden" name="removeAvatar" value="1" />}
      </div>

      {/* Core identity */}
      <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
        <h3 className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
          Identity
        </h3>
        <div className="mt-4 grid gap-4 md:grid-cols-2">
          <Field
            label="Full name"
            name="name"
            defaultValue={props.name}
            required
            error={state.fieldErrors?.name}
          />
          <Field
            label="Institution / hospital"
            name="institution"
            defaultValue={props.institution}
            required
            error={state.fieldErrors?.institution}
          />
          <SelectField
            label="Country"
            name="country"
            defaultValue={props.country}
            options={COUNTRIES}
            required
            error={state.fieldErrors?.country}
          />
          <SelectField
            label="Role"
            name="professionalRole"
            defaultValue={props.professionalRole}
            options={PROFESSIONAL_ROLES}
            required
            error={state.fieldErrors?.professionalRole}
          />
        </div>
      </div>

      {/* About you */}
      <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
        <h3 className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
          About you
        </h3>
        <p className="mt-1 text-[13px] text-[var(--color-slate)]">
          Shown on your directory profile.
        </p>
        <div className="mt-4 space-y-4">
          <TextArea
            label="Short bio (max 600 characters)"
            name="bio"
            defaultValue={props.bio}
            maxLength={600}
            rows={4}
          />
          <div className="grid gap-4 md:grid-cols-2">
            <Field
              label="Subspecialty"
              name="specialty"
              defaultValue={props.specialty}
              placeholder="e.g. Shoulder & elbow"
            />
            <Field
              label="Years qualified"
              name="yearsExperience"
              type="number"
              defaultValue={
                props.yearsExperience !== null
                  ? String(props.yearsExperience)
                  : ""
              }
              placeholder="0–80"
              error={state.fieldErrors?.yearsExperience}
            />
          </div>
        </div>
      </div>

      {/* Links */}
      <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
        <h3 className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
          Links
        </h3>
        <div className="mt-4 grid gap-4 md:grid-cols-2">
          <Field
            label="ORCID"
            name="orcidUrl"
            type="url"
            defaultValue={props.orcidUrl ?? ""}
            placeholder="https://orcid.org/0000-0000-0000-0000"
            error={state.fieldErrors?.orcidUrl}
          />
          <Field
            label="LinkedIn"
            name="linkedinUrl"
            type="url"
            defaultValue={props.linkedinUrl ?? ""}
            placeholder="https://linkedin.com/in/..."
            error={state.fieldErrors?.linkedinUrl}
          />
          <Field
            label="Website"
            name="websiteUrl"
            type="url"
            defaultValue={props.websiteUrl ?? ""}
            placeholder="https://yourclinic.example"
            error={state.fieldErrors?.websiteUrl}
          />
          <Field
            label="X / Twitter"
            name="twitterUrl"
            type="url"
            defaultValue={props.twitterUrl ?? ""}
            placeholder="https://x.com/handle"
            error={state.fieldErrors?.twitterUrl}
          />
        </div>
      </div>

      {/* Privacy */}
      <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
        <h3 className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
          Privacy
        </h3>
        <label className="mt-4 flex items-start gap-3 text-[13px]">
          <input
            type="checkbox"
            name="visibleInDirectory"
            defaultChecked={props.visibleInDirectory}
            className="mt-0.5 h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
          />
          <span>
            <span className="block font-semibold text-[var(--color-ink)]">
              Show me in the member directory
            </span>
            <span className="block text-[12px] text-[var(--color-slate)]">
              Other members see your name, institution, specialty, and bio.
              Your email, password, and private notes stay private.
            </span>
          </span>
        </label>
      </div>

      <Button type="submit" disabled={pending} variant="primary">
        {pending ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
            Saving…
          </>
        ) : (
          "Save profile"
        )}
      </Button>
    </form>
  );
}

function Field(props: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
  defaultValue?: string;
  placeholder?: string;
  error?: string;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {props.label}
        {props.required && <span className="ml-1 text-red-600">*</span>}
      </span>
      <input
        name={props.name}
        type={props.type ?? "text"}
        defaultValue={props.defaultValue}
        required={props.required}
        placeholder={props.placeholder}
        className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2 text-[14px] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
      />
      {props.error && (
        <span className="mt-1 block text-[12px] text-red-600">
          {props.error}
        </span>
      )}
    </label>
  );
}

function SelectField(props: {
  label: string;
  name: string;
  defaultValue?: string;
  options: readonly string[];
  required?: boolean;
  error?: string;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {props.label}
        {props.required && <span className="ml-1 text-red-600">*</span>}
      </span>
      <select
        name={props.name}
        defaultValue={props.defaultValue ?? ""}
        required={props.required}
        className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2 text-[14px] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
      >
        <option value="" disabled>
          Select…
        </option>
        {props.options.map((o) => (
          <option key={o} value={o}>
            {o}
          </option>
        ))}
      </select>
      {props.error && (
        <span className="mt-1 block text-[12px] text-red-600">
          {props.error}
        </span>
      )}
    </label>
  );
}

function TextArea(props: {
  label: string;
  name: string;
  defaultValue?: string;
  rows: number;
  maxLength?: number;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {props.label}
      </span>
      <textarea
        name={props.name}
        defaultValue={props.defaultValue}
        rows={props.rows}
        maxLength={props.maxLength}
        className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2 text-[14px] leading-relaxed focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
      />
    </label>
  );
}
