"use client";

import { useEffect, useState } from "react";
import { Plus, Trash2, Pencil, X, Users } from "lucide-react";
import MediaUploader, { type UploadResult } from "@/components/admin/MediaUploader";
import { ROLE_LABEL, RoleBadge } from "@/components/team/RoleBadge";
import type { TeamRole } from "@/models/TeamMember";

interface TeamMember {
  _id: string;
  name: string;
  displayName?: string;
  role: TeamRole;
  expertise: string[];
  bio?: string;
  discordTag?: string;
  avatarFileId?: string | null;
  socials?: { github?: string; linkedin?: string; twitter?: string };
}

export default function AdminTeamPage() {
  const [members, setMembers] = useState<TeamMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<TeamMember | null>(null);

  async function load() {
    setLoading(true);
    const res = await fetch("/api/team").then((r) => r.json());
    setMembers(res);
    setLoading(false);
  }

  useEffect(() => {
    load();
  }, []);

  async function deleteMember(id: string) {
    if (!confirm("Bu üyeyi silmek istiyor musunuz?")) return;
    await fetch(`/api/team/${id}`, { method: "DELETE" });
    load();
  }

  return (
    <div>
      <header className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-white inline-flex items-center gap-2">
            <Users className="w-6 h-6 text-brand-300" />
            Takım Yönetimi
          </h1>
          <p className="text-sm text-brand-300">
            Takım üyelerini ekleyin, düzenleyin veya kaldırın.
          </p>
        </div>
        <button
          className="btn-primary"
          onClick={() => {
            setEditing(null);
            setShowForm(true);
          }}
        >
          <Plus className="w-4 h-4" /> Yeni Üye
        </button>
      </header>

      {loading ? (
        <p className="text-brand-300">Yükleniyor...</p>
      ) : members.length === 0 ? (
        <div className="glass rounded-2xl p-10 text-center">
          <p className="text-brand-300">Henüz takım üyesi eklenmemiş.</p>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {members.map((m) => (
            <div key={m._id} className="glass rounded-xl p-4">
              <div className="flex items-start gap-3">
                {m.avatarFileId ? (
                  <img
                    src={`/api/files/${m.avatarFileId}`}
                    alt={m.name}
                    className="w-12 h-12 rounded-lg object-cover border border-brand-700/40"
                  />
                ) : (
                  <div className="w-12 h-12 rounded-lg bg-brand-700/40 border border-brand-700/40 flex items-center justify-center text-white font-bold">
                    {(m.displayName || m.name).slice(0, 2).toUpperCase()}
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-bold text-white truncate">
                    {m.displayName || m.name}
                  </div>
                  <div className="mt-1">
                    <RoleBadge role={m.role} size="sm" />
                  </div>
                </div>
              </div>
              {m.expertise.length > 0 && (
                <div className="mt-3 flex flex-wrap gap-1">
                  {m.expertise.slice(0, 4).map((e, i) => (
                    <span
                      key={i}
                      className="text-[10px] px-2 py-0.5 rounded-md bg-brand-700/40 text-brand-100"
                    >
                      {e}
                    </span>
                  ))}
                </div>
              )}
              <div className="mt-4 flex gap-2">
                <button
                  onClick={() => {
                    setEditing(m);
                    setShowForm(true);
                  }}
                  className="flex-1 inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded-md bg-brand-700/40 hover:bg-brand-700/60 text-xs text-white"
                >
                  <Pencil className="w-3 h-3" /> Düzenle
                </button>
                <button
                  onClick={() => deleteMember(m._id)}
                  className="px-2 py-1.5 rounded-md bg-red-500/20 hover:bg-red-500/40 text-xs text-red-200"
                  aria-label="Sil"
                >
                  <Trash2 className="w-3 h-3" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {showForm && (
        <TeamFormModal
          member={editing}
          onClose={() => {
            setShowForm(false);
            setEditing(null);
          }}
          onSaved={() => {
            setShowForm(false);
            setEditing(null);
            load();
          }}
        />
      )}
    </div>
  );
}

function TeamFormModal({
  member,
  onClose,
  onSaved,
}: {
  member: TeamMember | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [name, setName] = useState(member?.name ?? "");
  const [displayName, setDisplayName] = useState(member?.displayName ?? "");
  const [role, setRole] = useState<TeamRole>(member?.role ?? "design");
  const [expertise, setExpertise] = useState<string[]>(member?.expertise ?? []);
  const [expertInput, setExpertInput] = useState("");
  const [bio, setBio] = useState(member?.bio ?? "");
  const [discordTag, setDiscordTag] = useState(member?.discordTag ?? "");
  const [github, setGithub] = useState(member?.socials?.github ?? "");
  const [linkedin, setLinkedin] = useState(member?.socials?.linkedin ?? "");
  const [twitter, setTwitter] = useState(member?.socials?.twitter ?? "");

  const [avatar, setAvatar] = useState<UploadResult | null>(
    member?.avatarFileId
      ? {
          fileId: member.avatarFileId,
          contentType: "",
          mediaType: "image",
          size: 0,
          name: member.name,
        }
      : null,
  );
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function addExpertise() {
    const v = expertInput.trim();
    if (!v) return;
    if (expertise.includes(v)) return;
    setExpertise([...expertise, v]);
    setExpertInput("");
  }

  function removeExpertise(idx: number) {
    setExpertise(expertise.filter((_, i) => i !== idx));
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!name.trim()) return setError("İsim gerekli");

    setSaving(true);
    const payload = {
      name: name.trim(),
      displayName: displayName.trim(),
      role,
      expertise,
      bio,
      discordTag,
      avatarFileId: avatar?.fileId ?? null,
      socials: { github, linkedin, twitter },
    };

    const url = member ? `/api/team/${member._id}` : "/api/team";
    const method = member ? "PATCH" : "POST";
    const res = await fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    setSaving(false);
    if (!res.ok) {
      const d = await res.json();
      setError(d.error || "Hata");
      return;
    }
    onSaved();
  }

  return (
    <div
      className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0c1320] border border-brand-700/40 rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-5 border-b border-brand-700/30 flex items-center justify-between sticky top-0 bg-[#0c1320] z-10">
          <h3 className="text-lg font-bold text-white">
            {member ? "Üyeyi Düzenle" : "Yeni Üye"}
          </h3>
          <button onClick={onClose} className="text-brand-300 hover:text-white">
            <X className="w-5 h-5" />
          </button>
        </div>
        <form onSubmit={submit} className="p-5 space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm text-brand-200 mb-1">İsim</label>
              <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-brand-200 mb-1">
                Görünen İsim (opsiyonel)
              </label>
              <input
                value={displayName}
                onChange={(e) => setDisplayName(e.target.value)}
                placeholder="örn. Mustafa Y****"
                className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm text-brand-200 mb-1">Rol</label>
            <select
              value={role}
              onChange={(e) => setRole(e.target.value as TeamRole)}
              className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
            >
              {(Object.keys(ROLE_LABEL) as TeamRole[]).map((r) => (
                <option key={r} value={r}>
                  {ROLE_LABEL[r]}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm text-brand-200 mb-1">Bio</label>
            <textarea
              value={bio}
              onChange={(e) => setBio(e.target.value)}
              rows={3}
              placeholder="Kısa biyografi..."
              className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
            />
          </div>

          <div>
            <label className="block text-sm text-brand-200 mb-1">
              Uzmanlık Alanları
            </label>
            <div className="flex gap-2">
              <input
                value={expertInput}
                onChange={(e) => setExpertInput(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    addExpertise();
                  }
                }}
                placeholder="örn. Java, Spigot API, MySQL..."
                className="flex-1 bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-sm text-white outline-none focus:border-brand-400"
              />
              <button
                type="button"
                onClick={addExpertise}
                className="btn-secondary"
              >
                Ekle
              </button>
            </div>
            {expertise.length > 0 && (
              <div className="mt-2 flex flex-wrap gap-1.5">
                {expertise.map((e, i) => (
                  <span
                    key={i}
                    className="inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded bg-brand-700/40 text-xs text-white"
                  >
                    {e}
                    <button
                      type="button"
                      onClick={() => removeExpertise(i)}
                      className="w-4 h-4 rounded bg-red-500/30 hover:bg-red-500/50 flex items-center justify-center"
                    >
                      <X className="w-2.5 h-2.5" />
                    </button>
                  </span>
                ))}
              </div>
            )}
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm text-brand-200 mb-1">Discord Tag</label>
              <input
                value={discordTag}
                onChange={(e) => setDiscordTag(e.target.value)}
                placeholder="ornek#0001"
                className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
              />
            </div>
            <div>
              <label className="block text-sm text-brand-200 mb-1">GitHub URL</label>
              <input
                value={github}
                onChange={(e) => setGithub(e.target.value)}
                placeholder="https://github.com/..."
                className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
              />
            </div>
            <div>
              <label className="block text-sm text-brand-200 mb-1">LinkedIn URL</label>
              <input
                value={linkedin}
                onChange={(e) => setLinkedin(e.target.value)}
                className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
              />
            </div>
            <div>
              <label className="block text-sm text-brand-200 mb-1">Twitter URL</label>
              <input
                value={twitter}
                onChange={(e) => setTwitter(e.target.value)}
                className="w-full bg-brand-900/40 border border-brand-700/40 rounded-lg px-3 py-2 text-white outline-none focus:border-brand-400"
              />
            </div>
          </div>

          <MediaUploader
            value={avatar}
            onChange={setAvatar}
            label="Avatar (opsiyonel)"
            accept="image/png,image/jpeg,image/webp,image/gif"
          />

          {error && (
            <p className="text-sm text-red-300 bg-red-500/10 border border-red-500/30 rounded-lg p-3">
              {error}
            </p>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="btn-secondary">
              İptal
            </button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? "Kaydediliyor..." : member ? "Güncelle" : "Oluştur"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
