"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Pencil, Check, X, Loader2, Briefcase, MapPin, Link2, Calendar, Users,
} from "lucide-react";
import { Avatar } from "./Avatar";
import { sfx } from "@/lib/sfx";
import { useConnectionWords } from "@/lib/site-context";
import type { PublicProfile, User } from "@/lib/types";
import clsx from "clsx";

type Person = User & { isFollowing: boolean; isSelf: boolean };

/** "About" and "Friends" widgets for the profile's right column. */
export function ProfileAbout({
  profile,
  onSaved,
  onOpenConnections,
}: {
  profile: PublicProfile;
  onSaved: () => void;
  onOpenConnections: (kind: "followers" | "following" | "friends") => void;
}) {
  const cw = useConnectionWords();
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [work, setWork] = useState(profile.work ?? "");
  const [location, setLocation] = useState(profile.location ?? "");
  const [website, setWebsite] = useState(profile.website ?? "");
  const [bio, setBio] = useState(profile.bio ?? "");

  const [friends, setFriends] = useState<Person[] | null>(null);

  useEffect(() => {
    fetch(`/api/users/${profile.username}/connections?kind=friends`)
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setFriends(Array.isArray(d) ? d : []))
      .catch(() => setFriends([]));
  }, [profile.username]);

  async function save() {
    setSaving(true);
    await fetch("/api/me", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ work, location, website, bio }),
    }).catch(() => {});
    setSaving(false);
    setEditing(false);
    sfx.save();
    onSaved();
  }

  const rows = [
    { icon: Briefcase, value: profile.work, label: "Work" },
    { icon: MapPin, value: profile.location, label: "Lives in" },
    { icon: Link2, value: profile.website, label: "Website", link: true },
    {
      icon: Calendar,
      value: profile.joinedAt
        ? `Joined ${new Date(profile.joinedAt).toLocaleDateString(undefined, {
            month: "long",
            year: "numeric",
          })}`
        : undefined,
      label: "Joined",
    },
  ].filter((r) => r.value);

  return (
    <>
      <div className="pa-card">
        <h3>
          About
          {profile.isSelf && !editing && (
            <button onClick={() => setEditing(true)} className="pa-edit" title="Edit">
              <Pencil size={13} />
            </button>
          )}
        </h3>

        {editing ? (
          <div className="pa-form">
            <label>
              <span>Bio</span>
              <textarea
                value={bio}
                onChange={(e) => setBio(e.target.value.slice(0, 160))}
                rows={3}
                placeholder="Tell people about yourself"
              />
            </label>
            <label>
              <span>Work</span>
              <input
                value={work}
                onChange={(e) => setWork(e.target.value.slice(0, 60))}
                placeholder="What you do"
              />
            </label>
            <label>
              <span>Lives in</span>
              <input
                value={location}
                onChange={(e) => setLocation(e.target.value.slice(0, 60))}
                placeholder="Town or city"
              />
            </label>
            <label>
              <span>Website</span>
              <input
                value={website}
                onChange={(e) => setWebsite(e.target.value.slice(0, 80))}
                placeholder="example.com"
              />
            </label>

            <div className="pa-formbtns">
              <button onClick={save} disabled={saving} className="pa-save">
                {saving ? <Loader2 size={13} className="animate-spin" /> : <Check size={13} />}
                Save
              </button>
              <button onClick={() => setEditing(false)} className="pa-cancel">
                <X size={13} /> Cancel
              </button>
            </div>
          </div>
        ) : (
          <>
            {profile.bio && <p className="pa-bio">{profile.bio}</p>}
            {rows.map((r) => (
              <div key={r.label} className="pa-row">
                <span className="pa-icon">
                  <r.icon size={13} />
                </span>
                <span>
                  <em>{r.label}</em>
                  <b>{r.value}</b>
                </span>
              </div>
            ))}
            {rows.length === 0 && !profile.bio && (
              <p className="pa-empty">
                Nothing here yet.
                {profile.isSelf && " Tap the pencil to add your details."}
              </p>
            )}
          </>
        )}
      </div>

      <div className="pa-card">
        <h3>
          {cw.mode === "friend" ? cw.plural : "Mutuals"}
          <span className="pa-count">{friends?.length ?? 0}</span>
          <button
            onClick={() => onOpenConnections("friends")}
            className="pa-all"
          >
            See all
          </button>
        </h3>

        <div className="pa-friends">
          {friends?.slice(0, 9).map((f) => (
            <Link key={f.id} href={`/${f.username}`} className="pa-friend">
              <Avatar user={f} size={62} effect={false} />
              <span>{f.name.split(" ")[0]}</span>
            </Link>
          ))}
        </div>

        {friends?.length === 0 && (
          <p className="pa-empty">
            No mutual friends yet — following each other makes you friends.
          </p>
        )}
      </div>
    </>
  );
}
