"use client"

import * as React from "react"
import { UserAvatar } from "@/components/ui/user-avatar"
import { useGetTeamsQuery } from "@/api/rtk"

interface SettingsHeaderProps {
    profile?: {
        id?: string
        name: string
        avatar?: string | null
        role?: { name: string } | null
    } | null
}

export function SettingsHeader({ profile }: SettingsHeaderProps) {
    const { data: teams = [] } = useGetTeamsQuery(undefined, {
        skip: !profile?.id,
    })

    const isTeamLead = React.useMemo(() => {
        const userId = String(profile?.id ?? "")
        if (!userId) return false
        return teams.some(
            (team) =>
                team.teamLead?.userId === userId ||
                (team.lead != null && String(team.lead) === userId),
        )
    }, [teams, profile?.id])

    return (
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 rounded-2xl border border-white/40 bg-white/50 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] p-4 md:p-5">
            <div>
                <h1 className="text-[25px] font-extrabold text-gray-900 font-['Lexend'] tracking-tight leading-none">
                    Settings
                </h1>
                <p className="text-[12px] text-gray-400 mt-1.5 font-['Lexend_Deca']">
                    Manage your profile and system configuration
                </p>
            </div>
            {profile && (
                <div className="flex items-center gap-3 bg-gray-50/80 rounded-2xl p-2 pr-4 border border-gray-100">
                    <UserAvatar
                        avatar={profile.avatar}
                        name={profile.name}
                        size="sm"
                        className="rounded-lg"
                    />
                    <div className="text-left">
                        <p className="text-[13px] font-semibold text-gray-900 leading-none">{profile.name}</p>
                        <div className="mt-1 flex items-center gap-2">
                            <p className="text-[11px] text-gray-400 uppercase tracking-wider font-['Lexend_Deca']">
                                {profile.role?.name ?? "Member"}
                            </p>
                            {isTeamLead ? (
                                <span className="inline-flex items-center text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700">
                                    Team Lead
                                </span>
                            ) : null}
                        </div>
                    </div>
                </div>
            )}
        </div>
    )
}
