"use client";

import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";

export function ArchitectPhotoUploader({
  photoSrc,
  architectName,
}: {
  photoSrc?: string | null;
  architectName?: string;
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [ok, setOk] = useState<string | null>(null);
  const [previewSrc, setPreviewSrc] = useState<string | null>(photoSrc ?? null);

  useEffect(() => {
    setPreviewSrc(photoSrc ?? null);
  }, [photoSrc]);

  function onChange(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;

    setError(null);
    setOk(null);

    const localUrl = URL.createObjectURL(file);
    setPreviewSrc(localUrl);

    startTransition(async () => {
      const body = new FormData();
      body.set("file", file);

      const res = await fetch("/api/dashboard/architect-photo", {
        method: "POST",
        body,
      });

      const data = (await res.json()) as {
        error?: string;
        url?: string;
      };
      if (!res.ok) {
        setPreviewSrc(photoSrc ?? null);
        setError(data.error ?? "Upload failed");
        URL.revokeObjectURL(localUrl);
        return;
      }

      if (data.url) {
        setPreviewSrc(data.url);
      }
      URL.revokeObjectURL(localUrl);
      setOk("Photo updated");
      router.refresh();
      event.target.value = "";
    });
  }

  function onRemove() {
    setError(null);
    setOk(null);
    startTransition(async () => {
      const res = await fetch("/api/dashboard/architect-photo", {
        method: "DELETE",
      });
      const data = (await res.json()) as { error?: string };
      if (!res.ok) {
        setError(data.error ?? "Could not remove photo");
        return;
      }
      setPreviewSrc(null);
      setOk("Photo removed");
      router.refresh();
    });
  }

  const initial = (architectName?.trim()?.[0] || "A").toUpperCase();

  return (
    <div className="flex flex-col gap-5">
      <div className="relative mx-auto h-36 w-36 shrink-0 overflow-hidden rounded-[360px] border border-[var(--archi-line)] bg-[var(--archi-bg-deep)] sm:mx-0 sm:h-40 sm:w-40">
        {previewSrc ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={previewSrc}
            alt={
              architectName ? `${architectName} portrait` : "Architect portrait"
            }
            className="h-full w-full object-cover"
          />
        ) : (
          <div className="flex h-full w-full flex-col items-center justify-center gap-1 text-[var(--archi-ink-muted)]">
            <ProfileIcon className="h-9 w-9" />
            <span className="font-[family-name:var(--font-display)] text-lg">
              {initial}
            </span>
          </div>
        )}
      </div>

      <div className="min-w-0">
        <p className="text-sm font-medium">Architect profile photo</p>
        <p className="mt-1 text-xs leading-5 text-[var(--archi-ink-muted)]">
          Shown on your public studio home and About pages. Prefer a clear
          head-and-shoulders portrait (JPEG/PNG/WebP, max 8MB).
        </p>
        <div className="mt-4 flex flex-wrap gap-2">
          <label className="inline-flex min-h-10 cursor-pointer items-center border border-[var(--archi-line)] bg-white px-3.5 py-2 text-sm transition hover:border-[var(--archi-gold)]/40">
            <span>
              {pending
                ? "Working…"
                : previewSrc
                  ? "Replace photo"
                  : "Upload photo"}
            </span>
            <input
              type="file"
              accept="image/jpeg,image/png,image/webp,image/avif"
              className="sr-only"
              disabled={pending}
              onChange={onChange}
            />
          </label>
          {previewSrc ? (
            <button
              type="button"
              disabled={pending}
              onClick={onRemove}
              className="inline-flex min-h-10 items-center border border-[var(--archi-line)] px-3.5 py-2 text-sm text-red-800 transition hover:border-red-300 disabled:opacity-60"
            >
              Remove
            </button>
          ) : null}
        </div>
        {error ? (
          <p className="mt-3 text-sm text-red-800" role="alert">
            {error}
          </p>
        ) : null}
        {ok ? (
          <p className="mt-3 text-sm text-[var(--archi-gold)]" role="status">
            {ok}
          </p>
        ) : null}
      </div>
    </div>
  );
}

function ProfileIcon({ className = "h-6 w-6" }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      fill="none"
      aria-hidden
      stroke="currentColor"
      strokeWidth="1.5"
    >
      <circle cx="12" cy="8" r="3.25" />
      <path d="M5.5 19.5c1.4-3.2 3.7-4.75 6.5-4.75s5.1 1.55 6.5 4.75" />
    </svg>
  );
}
