/**
 * Teams page — List all teams user belongs to + create/join team.
 */

import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { PlusIcon, UsersIcon, LogInIcon, TrashIcon, LogOutIcon } from "lucide-react";
import { listTeams, createTeam, joinTeam, deleteTeam, leaveTeam } from "@/service/teamService";
import type { Team } from "@/service/teamService";

const Teams = () => {
    const navigate = useNavigate();
    const [teams, setTeams] = useState<Team[]>([]);
    const [loading, setLoading] = useState(true);
    const [showCreate, setShowCreate] = useState(false);
    const [showJoin, setShowJoin] = useState(false);
    const [newName, setNewName] = useState("");
    const [newDesc, setNewDesc] = useState("");
    const [inviteCode, setInviteCode] = useState("");
    const [error, setError] = useState("");

    const fetchTeams = async () => {
        try {
            setLoading(true);
            const data = await listTeams();
            setTeams(data);
        } catch (e: any) {
            setError(e.message);
        } finally {
            setLoading(false);
        }
    };

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

    const handleCreate = async () => {
        if (!newName.trim()) return;
        try {
            setError("");
            await createTeam(newName.trim(), newDesc.trim());
            setNewName("");
            setNewDesc("");
            setShowCreate(false);
            fetchTeams();
        } catch (e: any) {
            setError(e.message);
        }
    };

    const handleJoin = async () => {
        if (!inviteCode.trim()) return;
        try {
            setError("");
            await joinTeam(inviteCode.trim());
            setInviteCode("");
            setShowJoin(false);
            fetchTeams();
        } catch (e: any) {
            setError(e.message);
        }
    };

    const handleDelete = async (teamId: string) => {
        if (!confirm("Xóa team này? Tất cả memos sẽ bị mất.")) return;
        try {
            await deleteTeam(teamId);
            fetchTeams();
        } catch (e: any) {
            setError(e.message);
        }
    };

    const handleLeave = async (teamId: string) => {
        if (!confirm("Rời team này?")) return;
        try {
            await leaveTeam(teamId);
            fetchTeams();
        } catch (e: any) {
            setError(e.message);
        }
    };

    return (
        <div className="max-w-2xl mx-auto px-4 py-8">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-bold flex items-center gap-2">
                    <UsersIcon className="w-6 h-6" />
                    Teams
                </h1>
                <div className="flex gap-2">
                    <button
                        onClick={() => { setShowJoin(!showJoin); setShowCreate(false); }}
                        className="px-3 py-1.5 text-sm rounded-lg border border-border hover:bg-accent transition-colors flex items-center gap-1"
                    >
                        <LogInIcon className="w-4 h-4" />
                        Join
                    </button>
                    <button
                        onClick={() => { setShowCreate(!showCreate); setShowJoin(false); }}
                        className="px-3 py-1.5 text-sm rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition-colors flex items-center gap-1"
                    >
                        <PlusIcon className="w-4 h-4" />
                        New Team
                    </button>
                </div>
            </div>

            {error && (
                <div className="mb-4 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-sm">
                    {error}
                </div>
            )}

            {/* Create Team Form */}
            {showCreate && (
                <div className="mb-6 p-4 rounded-xl border border-border bg-card">
                    <h3 className="font-semibold mb-3">Tạo Team Mới</h3>
                    <input
                        type="text"
                        placeholder="Tên team..."
                        value={newName}
                        onChange={(e) => setNewName(e.target.value)}
                        className="w-full px-3 py-2 mb-2 rounded-lg border border-border bg-background text-sm"
                        autoFocus
                    />
                    <input
                        type="text"
                        placeholder="Mô tả (optional)..."
                        value={newDesc}
                        onChange={(e) => setNewDesc(e.target.value)}
                        className="w-full px-3 py-2 mb-3 rounded-lg border border-border bg-background text-sm"
                    />
                    <div className="flex gap-2 justify-end">
                        <button onClick={() => setShowCreate(false)} className="px-3 py-1.5 text-sm rounded-lg border border-border hover:bg-accent">
                            Hủy
                        </button>
                        <button onClick={handleCreate} className="px-3 py-1.5 text-sm rounded-lg bg-amber-500 text-white hover:bg-amber-600">
                            Tạo
                        </button>
                    </div>
                </div>
            )}

            {/* Join Team Form */}
            {showJoin && (
                <div className="mb-6 p-4 rounded-xl border border-border bg-card">
                    <h3 className="font-semibold mb-3">Join Team</h3>
                    <input
                        type="text"
                        placeholder="Paste invite code..."
                        value={inviteCode}
                        onChange={(e) => setInviteCode(e.target.value)}
                        className="w-full px-3 py-2 mb-3 rounded-lg border border-border bg-background text-sm"
                        autoFocus
                    />
                    <div className="flex gap-2 justify-end">
                        <button onClick={() => setShowJoin(false)} className="px-3 py-1.5 text-sm rounded-lg border border-border hover:bg-accent">
                            Hủy
                        </button>
                        <button onClick={handleJoin} className="px-3 py-1.5 text-sm rounded-lg bg-amber-500 text-white hover:bg-amber-600">
                            Join
                        </button>
                    </div>
                </div>
            )}

            {/* Team List */}
            {loading ? (
                <div className="text-center py-12 text-muted-foreground">Đang tải...</div>
            ) : teams.length === 0 ? (
                <div className="text-center py-16">
                    <UsersIcon className="w-12 h-12 mx-auto mb-4 text-muted-foreground/30" />
                    <p className="text-muted-foreground mb-2">Chưa có team nào</p>
                    <p className="text-sm text-muted-foreground/60">Tạo team mới hoặc join bằng invite code</p>
                </div>
            ) : (
                <div className="space-y-3">
                    {teams.map((team) => (
                        <div
                            key={team.id}
                            className="p-4 rounded-xl border border-border bg-card hover:border-amber-400/50 transition-all cursor-pointer group"
                            onClick={() => navigate(`/app/teams/${team.id}`)}
                        >
                            <div className="flex items-start justify-between">
                                <div className="flex-1 min-w-0">
                                    <h3 className="font-semibold text-base truncate group-hover:text-amber-500 transition-colors">
                                        {team.name}
                                    </h3>
                                    {team.description && (
                                        <p className="text-sm text-muted-foreground mt-0.5 truncate">{team.description}</p>
                                    )}
                                    <div className="flex items-center gap-3 mt-2 text-xs text-muted-foreground">
                                        <span className="flex items-center gap-1">
                                            <UsersIcon className="w-3.5 h-3.5" />
                                            {team.member_count} members
                                        </span>
                                        <span className="font-mono text-[10px] bg-muted px-1.5 py-0.5 rounded">
                                            {team.invite_code}
                                        </span>
                                    </div>
                                </div>
                                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => e.stopPropagation()}>
                                    {team.members?.some(m => m.role === "owner") ? (
                                        <button
                                            onClick={() => handleDelete(team.id)}
                                            className="p-1.5 rounded-lg text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20"
                                            title="Xóa team"
                                        >
                                            <TrashIcon className="w-4 h-4" />
                                        </button>
                                    ) : (
                                        <button
                                            onClick={() => handleLeave(team.id)}
                                            className="p-1.5 rounded-lg text-muted-foreground hover:bg-accent"
                                            title="Rời team"
                                        >
                                            <LogOutIcon className="w-4 h-4" />
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

export default Teams;
