'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Header from '@/components/Header';
import Footer from '@/components/Footer';

interface ForumProfile {
  username: string;
  display_name: string;
  bio: string | null;
  role_title: string | null;
  company: string | null;
  location_city: string | null;
  location_country: string | null;
  avatar_url: string | null;
}

export default function EditForumProfilePage() {
  const router = useRouter();
  const [profile, setProfile] = useState<ForumProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/forum/profile/me')
      .then(async (r) => {
        if (r.status === 401) {
          window.location.href = `/forum/login?next=${encodeURIComponent('/forum/profile/edit')}`;
          return null;
        }
        return r.json();
      })
      .then((d) => {
        if (d?.profile) setProfile(d.profile);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const update = (field: keyof ForumProfile, value: string) => {
    setProfile((p) => (p ? { ...p, [field]: value } : p));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!profile) return;
    setSaving(true);
    setError(null);
    setInfo(null);
    try {
      const res = await fetch('/api/forum/profile/me', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(profile),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || `Update failed (${res.status})`);
      setProfile(data.profile);
      setInfo('Profile saved.');
      setTimeout(() => router.push(`/forum/user/${data.profile.username}`), 800);
    } catch (err: any) {
      setError(err.message || 'Failed to save profile.');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <>
        <Header />
        <main className="min-h-screen bg-[#F8FAFC]">
          <div className="max-w-2xl mx-auto px-4 py-12 text-[#666] font-body text-sm">Loading…</div>
        </main>
        <Footer />
      </>
    );
  }

  if (!profile) {
    return (
      <>
        <Header />
        <main className="min-h-screen bg-[#F8FAFC]">
          <div className="max-w-2xl mx-auto px-4 py-12 text-[#888] font-body text-sm">
            Profile unavailable.
          </div>
        </main>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Header />
      <main className="min-h-screen bg-[#F8FAFC]">
        <div className="max-w-2xl mx-auto px-4 py-8">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-2xl font-heading font-bold text-white">Edit Profile</h1>
            <Link
              href={`/forum/user/${profile.username}`}
              className="text-xs font-body text-[#1D4ED8] hover:underline"
            >
              View public profile →
            </Link>
          </div>

          <form
            onSubmit={handleSubmit}
            className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-lg p-6 space-y-4"
          >
            {error && (
              <div className="bg-[#2a0a0a] border border-[#1D4ED8] text-[#ff8a8a] font-body text-sm px-3 py-2 rounded">
                {error}
              </div>
            )}
            {info && (
              <div className="bg-[#0a2a14] border border-[#1e8c3f] text-[#7fffaa] font-body text-sm px-3 py-2 rounded">
                {info}
              </div>
            )}

            <Field label="Username (URL handle)">
              <input
                type="text"
                value={profile.username}
                onChange={(e) => update('username', e.target.value)}
                pattern="[A-Za-z0-9_]{3,24}"
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
              <p className="text-[11px] font-body text-[#666] mt-1">
                3-24 characters. Letters, numbers, underscore.
              </p>
            </Field>

            <Field label="Display name">
              <input
                type="text"
                value={profile.display_name}
                onChange={(e) => update('display_name', e.target.value)}
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </Field>

            <Field label="Bio">
              <textarea
                value={profile.bio || ''}
                onChange={(e) => update('bio', e.target.value)}
                rows={4}
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8] resize-none"
              />
            </Field>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Field label="Role / Title">
                <input
                  type="text"
                  value={profile.role_title || ''}
                  onChange={(e) => update('role_title', e.target.value)}
                  className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
                />
              </Field>
              <Field label="Company">
                <input
                  type="text"
                  value={profile.company || ''}
                  onChange={(e) => update('company', e.target.value)}
                  className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
                />
              </Field>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Field label="City">
                <input
                  type="text"
                  value={profile.location_city || ''}
                  onChange={(e) => update('location_city', e.target.value)}
                  className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
                />
              </Field>
              <Field label="Country">
                <input
                  type="text"
                  value={profile.location_country || ''}
                  onChange={(e) => update('location_country', e.target.value)}
                  className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
                />
              </Field>
            </div>

            <Field label="Avatar URL">
              <input
                type="url"
                value={profile.avatar_url || ''}
                onChange={(e) => update('avatar_url', e.target.value)}
                placeholder="https://…"
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </Field>

            <button
              type="submit"
              disabled={saving}
              className="bg-[#1D4ED8] hover:bg-[#1E3A8A] disabled:opacity-50 text-white font-body font-semibold text-sm px-5 py-2.5 rounded-lg transition-colors"
            >
              {saving ? 'Saving…' : 'Save Profile'}
            </button>
          </form>
        </div>
      </main>
      <Footer />
    </>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
        {label}
      </label>
      {children}
    </div>
  );
}
