"use client";

import { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Users, UserPlus, Shield, Eye, Code, Crown, Trash2, Mail } from "lucide-react";

interface TeamMember {
  id: string;
  name: string | null;
  email: string;
  teamRole: string | null;
  createdAt: string;
}

interface PendingInvite {
  id: string;
  email: string;
  role: string;
  createdAt: string;
  expiresAt: string;
}

interface TeamData {
  id: string;
  name: string;
  owner: { id: string; name: string | null; email: string };
  members: TeamMember[];
  invites: PendingInvite[];
  maxSeats: number;
}

const roleIcons: Record<string, React.ReactNode> = {
  admin: <Shield size={14} className="text-amber-400" />,
  developer: <Code size={14} className="text-blue-400" />,
  viewer: <Eye size={14} className="text-gray-400" />,
};

export default function TeamPage() {
  const { data: session } = useSession();
  const plan = (session?.user as Record<string, unknown>)?.plan as string | undefined;
  const isTeamPlan = plan === "team" || plan === "enterprise";

  const [team, setTeam] = useState<TeamData | null>(null);
  const [userRole, setUserRole] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  // Create team state
  const [teamName, setTeamName] = useState("");
  const [creating, setCreating] = useState(false);

  // Invite state
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] = useState("developer");
  const [inviting, setInviting] = useState(false);

  const fetchTeam = useCallback(async () => {
    try {
      const res = await fetch("/api/team");
      if (res.ok) {
        const data = await res.json();
        setTeam(data.team);
        setUserRole(data.userRole);
      }
    } catch {
      setError("Failed to load team");
    } finally {
      setLoading(false);
    }
  }, []);

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

  const createTeam = async () => {
    if (!teamName.trim()) return;
    setCreating(true);
    setError("");

    try {
      const res = await fetch("/api/team", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: teamName }),
      });

      if (res.ok) {
        setTeamName("");
        await fetchTeam();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to create team");
      }
    } catch {
      setError("Failed to create team");
    } finally {
      setCreating(false);
    }
  };

  const inviteMember = async () => {
    if (!inviteEmail.trim()) return;
    setInviting(true);
    setError("");

    try {
      const res = await fetch("/api/team/invite", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: inviteEmail, role: inviteRole }),
      });

      if (res.ok) {
        setInviteEmail("");
        await fetchTeam();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to send invite");
      }
    } catch {
      setError("Failed to send invite");
    } finally {
      setInviting(false);
    }
  };

  const updateRole = async (memberId: string, role: string) => {
    try {
      const res = await fetch("/api/team/members", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ memberId, role }),
      });

      if (res.ok) {
        await fetchTeam();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to update role");
      }
    } catch {
      setError("Failed to update role");
    }
  };

  const removeMember = async (memberId: string) => {
    if (!confirm("Remove this member from the team?")) return;

    try {
      const res = await fetch("/api/team/members", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ memberId }),
      });

      if (res.ok) {
        await fetchTeam();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to remove member");
      }
    } catch {
      setError("Failed to remove member");
    }
  };

  const revokeInvite = async (inviteId: string) => {
    try {
      const res = await fetch("/api/team/invite", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ inviteId }),
      });

      if (res.ok) {
        await fetchTeam();
      }
    } catch {
      setError("Failed to revoke invite");
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-indigo-400 border-t-transparent" />
      </div>
    );
  }

  // No team plan — show upgrade prompt
  if (!isTeamPlan && !team) {
    return (
      <div className="mx-auto max-w-2xl space-y-6">
        <h1 className="text-2xl font-bold text-gray-100">Team Management</h1>
        <Card className="border-gray-800 bg-gray-900 p-8 text-center">
          <Users className="mx-auto mb-4 h-12 w-12 text-gray-500" />
          <h2 className="mb-2 text-lg font-semibold text-gray-200">
            Team features require a Team or Enterprise plan
          </h2>
          <p className="mb-6 text-sm text-gray-400">
            Upgrade to manage team members, set roles, track per-developer spending,
            and share configurations across your organization.
          </p>
          <a href="/dashboard/settings">
            <Button variant="primary">Upgrade to Team Plan</Button>
          </a>
        </Card>
      </div>
    );
  }

  // Has team plan but no team created yet
  if (!team) {
    return (
      <div className="mx-auto max-w-2xl space-y-6">
        <h1 className="text-2xl font-bold text-gray-100">Create Your Team</h1>
        <Card className="border-gray-800 bg-gray-900 p-6">
          <p className="mb-4 text-sm text-gray-400">
            Create a team to invite members, assign roles, and manage shared configurations.
          </p>
          {error && (
            <div className="mb-4 rounded-lg border border-red-800 bg-red-900/30 p-3 text-sm text-red-300">
              {error}
            </div>
          )}
          <div className="flex gap-3">
            <Input
              value={teamName}
              onChange={(e) => setTeamName(e.target.value)}
              placeholder="Team name (e.g., Acme AI Lab)"
              className="flex-1"
              onKeyDown={(e) => e.key === "Enter" && createTeam()}
            />
            <Button variant="primary" onClick={createTeam} disabled={creating || !teamName.trim()}>
              {creating ? "Creating..." : "Create Team"}
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  // Team dashboard
  const isAdmin = userRole === "admin";

  return (
    <div className="mx-auto max-w-4xl space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-100">{team.name}</h1>
          <p className="text-sm text-gray-400">
            {team.members.length} / {team.maxSeats} seats used
          </p>
        </div>
      </div>

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

      {/* Invite Member (admin only) */}
      {isAdmin && (
        <Card className="border-gray-800 bg-gray-900 p-5">
          <h2 className="mb-3 flex items-center gap-2 text-sm font-semibold text-gray-200">
            <UserPlus size={16} /> Invite Member
          </h2>
          <div className="flex flex-wrap gap-3">
            <Input
              value={inviteEmail}
              onChange={(e) => setInviteEmail(e.target.value)}
              placeholder="colleague@company.com"
              type="email"
              className="min-w-[200px] flex-1"
              onKeyDown={(e) => e.key === "Enter" && inviteMember()}
            />
            <select
              value={inviteRole}
              onChange={(e) => setInviteRole(e.target.value)}
              className="rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200"
            >
              <option value="developer">Developer</option>
              <option value="admin">Admin</option>
              <option value="viewer">Viewer</option>
            </select>
            <Button variant="primary" onClick={inviteMember} disabled={inviting || !inviteEmail.trim()}>
              {inviting ? "Sending..." : "Send Invite"}
            </Button>
          </div>
        </Card>
      )}

      {/* Members List */}
      <Card className="border-gray-800 bg-gray-900 p-5">
        <h2 className="mb-4 flex items-center gap-2 text-sm font-semibold text-gray-200">
          <Users size={16} /> Members
        </h2>
        <div className="space-y-2">
          {team.members.map((member) => (
            <div
              key={member.id}
              className="flex items-center justify-between rounded-lg border border-gray-800 bg-gray-800/30 px-4 py-3"
            >
              <div className="flex items-center gap-3">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-700 text-sm font-medium text-gray-200">
                  {(member.name ?? member.email)[0].toUpperCase()}
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium text-gray-100">
                      {member.name ?? member.email}
                    </span>
                    {member.id === team.owner.id && (
                      <Crown size={12} className="text-amber-400" />
                    )}
                  </div>
                  <span className="text-xs text-gray-500">{member.email}</span>
                </div>
              </div>

              <div className="flex items-center gap-3">
                {isAdmin && member.id !== session?.user?.id ? (
                  <>
                    <select
                      value={member.teamRole ?? "developer"}
                      onChange={(e) => updateRole(member.id, e.target.value)}
                      className="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-300"
                    >
                      <option value="admin">Admin</option>
                      <option value="developer">Developer</option>
                      <option value="viewer">Viewer</option>
                    </select>
                    {member.id !== team.owner.id && (
                      <button
                        onClick={() => removeMember(member.id)}
                        className="text-gray-500 hover:text-red-400"
                        title="Remove member"
                      >
                        <Trash2 size={14} />
                      </button>
                    )}
                  </>
                ) : (
                  <span className="flex items-center gap-1 text-xs text-gray-400">
                    {roleIcons[member.teamRole ?? "developer"]}
                    <span className="capitalize">{member.teamRole ?? "developer"}</span>
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Pending Invites */}
      {isAdmin && team.invites.length > 0 && (
        <Card className="border-gray-800 bg-gray-900 p-5">
          <h2 className="mb-4 flex items-center gap-2 text-sm font-semibold text-gray-200">
            <Mail size={16} /> Pending Invites
          </h2>
          <div className="space-y-2">
            {team.invites.map((invite) => (
              <div
                key={invite.id}
                className="flex items-center justify-between rounded-lg border border-gray-800 bg-gray-800/30 px-4 py-3"
              >
                <div>
                  <span className="text-sm text-gray-200">{invite.email}</span>
                  <span className="ml-2 rounded bg-gray-700 px-2 py-0.5 text-xs text-gray-400 capitalize">
                    {invite.role}
                  </span>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-xs text-gray-500">
                    Expires {new Date(invite.expiresAt).toLocaleDateString()}
                  </span>
                  <button
                    onClick={() => revokeInvite(invite.id)}
                    className="text-gray-500 hover:text-red-400"
                    title="Revoke invite"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}
