import React, { useState, useCallback, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { teamApi } from '../api/team';
import type { TeamMember, CompanyRole } from '../types';
import { AppLayout } from '../components/layout/AppLayout';
import { PageLoader } from '../components/ui/LoadingSpinner';
import { useAuth } from '../contexts/AuthContext';
import {
  Users,
  Mail,
  ChevronDown,
  Check,
  Loader2,
  X,
  AlertTriangle,
  UserMinus,
  UserPlus,
  UserCheck,
} from 'lucide-react';

const COMPANY_ROLES: { value: CompanyRole; label: string; color: string }[] = [
  { value: 'owner', label: 'Owner', color: 'bg-purple-100 text-purple-700' },
  { value: 'admin', label: 'Admin', color: 'bg-indigo-100 text-indigo-700' },
  { value: 'manager', label: 'Manager', color: 'bg-amber-100 text-amber-700' },
  { value: 'rep', label: 'Rep', color: 'bg-emerald-100 text-emerald-700' },
  { value: 'viewer', label: 'Viewer', color: 'bg-slate-100 text-slate-600' },
];

function RoleBadge({ role }: { role: CompanyRole }) {
  const config = COMPANY_ROLES.find((r) => r.value === role);
  return (
    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
      {config?.label || role}
    </span>
  );
}

function RoleDropdown({
  memberId,
  currentRole,
  disabled,
}: {
  memberId: number;
  currentRole: CompanyRole;
  disabled?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [rect, setRect] = useState<DOMRect | null>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: ({ userId, role }: { userId: number; role: CompanyRole }) =>
      teamApi.updateRole(userId, role),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['team'] });
      setOpen(false);
    },
  });

  useEffect(() => {
    if (open && triggerRef.current) {
      setRect(triggerRef.current.getBoundingClientRect());
    }
  }, [open]);

  const handleChange = (newRole: CompanyRole) => {
    if (newRole === currentRole) return;
    mutation.mutate({ userId: memberId, role: newRole });
  };

  const config = COMPANY_ROLES.find((r) => r.value === currentRole);

  const dropdownContent = (
    <div
      className="w-40 rounded-lg border border-surface-200 bg-white shadow-lg py-1"
      style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.right - 160 : 0, zIndex: 100 }}
    >
      {COMPANY_ROLES.map((role) => (
        <button
          key={role.value}
          onClick={() => handleChange(role.value)}
          disabled={disabled}
          className="flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-surface-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {currentRole === role.value && <Check className="h-3.5 w-3.5 text-brand-600" />}
          <span className={currentRole === role.value ? 'text-brand-700 font-medium' : 'text-surface-700'}>
            {role.label}
          </span>
        </button>
      ))}
    </div>
  );

  return (
    <div className="relative">
      <button
        ref={triggerRef}
        onClick={() => !disabled && setOpen(!open)}
        disabled={mutation.isPending || disabled}
        className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium disabled:opacity-50 min-w-[80px] justify-center ${
          disabled ? 'cursor-not-allowed' : 'hover:opacity-80'
        }`}
      >
        {mutation.isPending ? (
          <Loader2 className="h-3 w-3 animate-spin" />
        ) : (
          <>
            <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
              {config?.label || currentRole}
            </span>
            {!disabled && <ChevronDown className="h-3 w-3 text-surface-400" />}
          </>
        )}
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
          {createPortal(dropdownContent, document.body)}
        </>
      )}
    </div>
  );
}

/* ─── Invite Member Modal ─────────────────────────────────────── */
function InviteMemberModal({
  onClose,
  onInvite,
  isPending,
  currentUserEmail,
}: {
  onClose: () => void;
  onInvite: (member: { email: string; name: string; role: CompanyRole }) => void;
  isPending: boolean;
  currentUserEmail: string;
}) {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [role, setRole] = useState<CompanyRole>('viewer');
  const [error, setError] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!email.trim()) {
      setError('Email is required');
      return;
    }

    if (email.toLowerCase() === currentUserEmail.toLowerCase()) {
      setError('You are already a team member');
      return;
    }

    onInvite({ email: email.trim(), name: name.trim(), role });
  };

  return createPortal(
    <div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative w-full max-w-md rounded-xl bg-white shadow-xl">
        <div className="flex items-center justify-between border-b border-surface-200 p-5">
          <div className="flex items-center gap-2">
            <UserPlus className="h-5 w-5 text-brand-600" />
            <h2 className="text-lg font-semibold text-surface-900">Invite Team Member</h2>
          </div>
          <button onClick={onClose} className="rounded-md p-1 text-surface-400 hover:text-surface-600">
            <X className="h-5 w-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Email *</label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-surface-400" />
              <input
                type="email"
                required
                value={email}
                onChange={(e) => { setEmail(e.target.value); setError(''); }}
                className="w-full rounded-lg border border-surface-300 py-2 pl-10 pr-3 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100"
                placeholder="colleague@company.com"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Full Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100"
              placeholder="Jane Smith"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-surface-700 mb-1">Role</label>
            <select
              value={role}
              onChange={(e) => setRole(e.target.value as CompanyRole)}
              className="w-full rounded-lg border border-surface-300 py-2 px-3 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100"
            >
              {COMPANY_ROLES.map((r) => (
                <option key={r.value} value={r.value}>{r.label}</option>
              ))}
            </select>
            <p className="mt-1 text-xs text-surface-500">
              {role === 'viewer' && 'Can view dashboards and reports only.'}
              {role === 'rep' && 'Can view and manage their own data.'}
              {role === 'manager' && 'Can manage team, view analytics, and edit integrations.'}
              {role === 'admin' && 'Full access including team and settings management.'}
              {role === 'owner' && 'Complete control over the organization.'}
            </p>
          </div>
          {error && (
            <p className="text-sm text-red-600">{error}</p>
          )}
          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isPending}
              className="flex-1 rounded-lg border border-surface-300 py-2.5 px-4 text-sm font-medium text-surface-700 hover:bg-surface-50 disabled:opacity-50 min-h-[44px]"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isPending}
              className="flex-1 rounded-lg bg-brand-600 py-2.5 px-4 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50 min-h-[44px]"
            >
              {isPending ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : 'Invite Member'}
            </button>
          </div>
        </form>
      </div>
    </div>,
    document.body
  );
}

/* ─── Remove Member Confirmation Modal ────────────────────────── */
function RemoveMemberModal({
  member,
  onConfirm,
  onClose,
  isPending,
  isOwner,
}: {
  member: TeamMember;
  onConfirm: () => void;
  onClose: () => void;
  isPending: boolean;
  isOwner: boolean;
}) {
  return createPortal(
    <div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative w-full max-w-sm rounded-xl bg-white shadow-xl p-6 text-center">
        <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
          <AlertTriangle className="h-6 w-6 text-red-600" />
        </div>
        <h3 className="text-lg font-semibold text-surface-900 mb-2">
          Remove Team Member
        </h3>
        <p className="text-sm text-surface-500 mb-1">
          Are you sure you want to remove{' '}
          <strong className="text-surface-700">{member.name}</strong>?
        </p>
        <p className="text-xs text-surface-400 mb-6">
          {member.email} will lose access to the organization.
        </p>
        {isOwner && (
          <p className="text-xs text-amber-600 mb-4 bg-amber-50 rounded-md px-3 py-2">
            This member is an <strong>Owner</strong>. They will retain their ownership status but lose access to this organization.
          </p>
        )}
        <div className="flex gap-3">
          <button
            onClick={onClose}
            disabled={isPending}
            className="flex-1 rounded-lg border border-surface-300 py-2.5 px-4 text-sm font-medium text-surface-700 hover:bg-surface-50 disabled:opacity-50 min-h-[44px]"
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            disabled={isPending}
            className="flex-1 rounded-lg bg-red-600 py-2.5 px-4 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50 min-h-[44px]"
          >
            {isPending ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : 'Remove'}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}

/* ─── Main Team Page ─────────────────────────────────────────── */
export function TeamPage() {
  const { user } = useAuth();
  const queryClient = useQueryClient();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['team'],
    queryFn: () => teamApi.getTeam(),
  });

  const members = data?.items ?? [];
  const currentUserEmail = user?.email ?? '';

  // Invite mutation
  const inviteMutation = useMutation({
    mutationFn: (member: { email: string; name: string; role: CompanyRole }) =>
      teamApi.addMember(member),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['team'] });
    },
  });

  // Remove mutation
  const removeMutation = useMutation({
    mutationFn: (userId: number) => teamApi.removeMember(userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['team'] });
    },
  });

  // State for modals
  const [showInviteModal, setShowInviteModal] = useState(false);
  const [removeTarget, setRemoveTarget] = useState<TeamMember | null>(null);

  const canManageRole = useCallback((member: TeamMember): boolean => {
    // Owner can manage everyone
    if (user?.companyRole === 'owner') return true;
    // Admin can manage everyone except owners
    if (user?.companyRole === 'admin') return member.role !== 'owner';
    // Manager can manage reps and viewers
    if (user?.companyRole === 'manager') return ['rep', 'viewer'].includes(member.role);
    return false;
  }, [user?.companyRole]);

  if (isLoading) {
    return (
      <AppLayout title="Team">
        <PageLoader />
      </AppLayout>
    );
  }

  return (
    <AppLayout title="Team">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold text-surface-900">Team</h1>
          <p className="mt-1 text-sm text-surface-500">
            {members.length} team member{members.length !== 1 ? 's' : ''} in your organization
          </p>
        </div>
        <button
          onClick={() => setShowInviteModal(true)}
          className="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 min-h-[44px] w-full sm:w-auto"
        >
          <UserPlus className="h-4 w-4" />
          Invite Member
        </button>
      </div>

      {/* Error state */}
      {isError ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-surface-200 bg-white py-16">
          <AlertTriangle className="h-12 w-12 text-red-400" />
          <p className="mt-4 text-sm font-medium text-surface-700">Failed to load team members</p>
          <button
            onClick={() => queryClient.invalidateQueries({ queryKey: ['team'] })}
            className="mt-3 text-sm text-brand-600 hover:text-brand-700"
          >
            Try again
          </button>
        </div>
      ) : members.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-surface-200 bg-white py-16">
          <Users className="h-12 w-12 text-surface-300" />
          <p className="mt-4 text-sm font-medium text-surface-700">No team members yet</p>
          <p className="mt-1 text-xs text-surface-500">Invite your first team member to get started.</p>
        </div>
      ) : (
        <div className="rounded-xl border border-surface-200 bg-white">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-surface-200">
                  <th className="pb-3 pl-5 text-left font-medium text-surface-500">Member</th>
                  <th className="pb-3 text-left font-medium text-surface-500">Role</th>
                  <th className="pb-3 text-left font-medium text-surface-500">Status</th>
                  <th className="pb-3 text-right font-medium text-surface-500 pr-2">Last Login</th>
                  <th className="pb-3 pr-5 w-10"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-surface-100">
                {members.map((member) => {
                  const isSelf = member.email === currentUserEmail;
                  const canManage = canManageRole(member);

                  return (
                    <tr key={member.id} className="hover:bg-surface-50">
                      <td className="py-3 pl-5">
                        <div className="flex items-center gap-3">
                          <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-brand-100 text-xs font-semibold text-brand-700">
                            {member.name.charAt(0).toUpperCase()}
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-sm font-medium text-surface-900 truncate">
                              {member.name}
                              {isSelf && (
                                <span className="ml-1.5 text-[10px] font-normal text-surface-400">(you)</span>
                              )}
                            </p>
                            <p className="text-xs text-surface-500 truncate">{member.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="py-3">
                        <RoleDropdown
                          memberId={member.id}
                          currentRole={member.role}
                          disabled={!canManage || member.role === 'owner' && !isSelf}
                        />
                      </td>
                      <td className="py-3">
                        <span
                          className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                            member.status === 'active'
                              ? 'bg-emerald-50 text-emerald-700'
                              : 'bg-surface-100 text-surface-500'
                          }`}
                        >
                          {member.status === 'active' ? (
                            <>
                              <UserCheck className="mr-1 h-3 w-3" />
                              Active
                            </>
                          ) : (
                            member.status
                          )}
                        </span>
                      </td>
                      <td className="py-3 text-right text-surface-500 pr-2">
                        {member.lastLogin ? new Date(member.lastLogin).toLocaleDateString() : 'Never'}
                      </td>
                      <td className="py-3 pr-5 text-right">
                        {!isSelf && (
                          <button
                            onClick={() => setRemoveTarget(member)}
                            className="inline-flex items-center justify-center rounded-md p-1.5 text-surface-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                            title="Remove member"
                          >
                            <UserMinus className="h-4 w-4" />
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Invite Member Modal */}
      {showInviteModal && (
        <InviteMemberModal
          onClose={() => setShowInviteModal(false)}
          onInvite={(member) => inviteMutation.mutate(member)}
          isPending={inviteMutation.isPending}
          currentUserEmail={currentUserEmail}
        />
      )}

      {/* Remove Member Modal */}
      {removeTarget && (
        <RemoveMemberModal
          member={removeTarget}
          onConfirm={() => {
            removeMutation.mutate(removeTarget.id);
            setRemoveTarget(null);
          }}
          onClose={() => setRemoveTarget(null)}
          isPending={removeMutation.isPending}
          isOwner={removeTarget.role === 'owner'}
        />
      )}
    </AppLayout>
  );
}
