/**
 * Team Management Page
 * Tabs: Users, Invitations, Access Control
 */

import { useState, useEffect } from 'react';
import { Users, UserPlus, Shield } from 'lucide-react';
import PageMeta from '../../components/common/PageMeta';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { getTeamMembers, inviteTeamMember, removeTeamMember, TeamMember } from '../../services/billing.api';
import { Card } from '../../components/ui/card';
import Button from '../../components/ui/button/Button';
import Badge from '../../components/ui/badge/Badge';

type TabType = 'users' | 'invitations' | 'access';

export default function TeamManagementPage() {
  const toast = useToast();
  const [activeTab, setActiveTab] = useState<TabType>('users');
  const [members, setMembers] = useState<TeamMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [showInviteModal, setShowInviteModal] = useState(false);
  const [inviting, setInviting] = useState(false);
  const [inviteForm, setInviteForm] = useState({
    email: '',
    first_name: '',
    last_name: '',
  });

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

  const loadTeamMembers = async () => {
    try {
      setLoading(true);
      const data = await getTeamMembers();
      setMembers(data.results || []);
    } catch (error: any) {
      toast.error(`Failed to load team members: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleInvite = async () => {
    if (!inviteForm.email) {
      toast.error('Email is required');
      return;
    }

    try {
      setInviting(true);
      const result = await inviteTeamMember(inviteForm);
      toast.success(result.message || 'Team member invited successfully');
      setShowInviteModal(false);
      setInviteForm({ email: '', first_name: '', last_name: '' });
      await loadTeamMembers();
    } catch (error: any) {
      toast.error(`Failed to invite team member: ${error.message}`);
    } finally {
      setInviting(false);
    }
  };

  const handleRemove = async (userId: number, email: string) => {
    if (!confirm(`Are you sure you want to remove ${email} from the team?`)) {
      return;
    }

    try {
      const result = await removeTeamMember(userId);
      toast.success(result.message || 'Team member removed successfully');
      await loadTeamMembers();
    } catch (error: any) {
      toast.error(`Failed to remove team member: ${error.message}`);
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <PageMeta title="Team Management" description="Manage your team members" />
        <div className="flex items-center justify-center h-64">
          <div className="text-gray-500">Loading...</div>
        </div>
      </div>
    );
  }

  const tabs = [
    { id: 'users' as TabType, label: 'Users', icon: <Users className="w-4 h-4" /> },
    { id: 'invitations' as TabType, label: 'Invitations', icon: <UserPlus className="w-4 h-4" /> },
    { id: 'access' as TabType, label: 'Access Control', icon: <Shield className="w-4 h-4" /> },
  ];

  return (
    <div className="p-6">
      <PageMeta title="Team Management" description="Manage your team members" />
      
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Team Management</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Manage team members, invitations, and access control
        </p>
      </div>

      {/* Tabs */}
      <div className="mb-6 border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8">
          {tabs.map((tab) => (
            <button
              type="button"
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                flex items-center gap-2 py-4 px-1 border-b-2 font-medium text-sm
                ${activeTab === tab.id
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400'
                }
              `}
            >
              {tab.icon}
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Users Tab */}
      {activeTab === 'users' && (
        <div className="space-y-6">
          <div className="flex justify-end">
            <Button
              variant="primary"
              tone="brand"
              size="md"
              startIcon={<UserPlus className="w-4 h-4" />}
              onClick={() => setShowInviteModal(true)}
            >
              Invite Team Member
            </Button>
          </div>

          {/* Team Members Table */}
          <Card className="p-6">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Name</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Email</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Status</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Role</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Joined</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Last Login</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Actions</th>
              </tr>
            </thead>
            <tbody>
              {members.map((member) => (
                <tr key={member.id} className="border-b border-gray-100 dark:border-gray-800">
                  <td className="py-3 px-4 text-sm text-gray-900 dark:text-white">
                    {member.first_name || member.last_name 
                      ? `${member.first_name} ${member.last_name}`.trim()
                      : '-'}
                  </td>
                  <td className="py-3 px-4 text-sm text-gray-900 dark:text-white">
                    {member.email}
                  </td>
                  <td className="py-3 px-4">
                    <Badge 
                      variant="light" 
                      color={member.is_active ? 'success' : 'error'}
                    >
                      {member.is_active ? 'Active' : 'Inactive'}
                    </Badge>
                  </td>
                  <td className="py-3 px-4 text-sm text-gray-600 dark:text-gray-400">
                    {member.is_staff ? 'Admin' : 'Member'}
                  </td>
                  <td className="py-3 px-4 text-sm text-gray-600 dark:text-gray-400">
                    {member.date_joined ? new Date(member.date_joined).toLocaleDateString() : 'N/A'}
                  </td>
                  <td className="py-3 px-4 text-sm text-gray-600 dark:text-gray-400">
                    {member.last_login ? new Date(member.last_login).toLocaleDateString() : 'Never'}
                  </td>
                  <td className="py-3 px-4 text-right">
                    <Button
                      variant="secondary"
                      size="sm"
                      onClick={() => handleRemove(member.id, member.email)}
                    >
                      Remove
                    </Button>
                  </td>
                </tr>
              ))}
              {members.length === 0 && (
                <tr>
                  <td colSpan={7} className="py-8 text-center text-gray-500 dark:text-gray-400">
                    No team members yet. Invite your first team member!
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  )}

  {/* Invitations Tab */}
  {activeTab === 'invitations' && (
    <div className="space-y-6">
      <div className="flex justify-end">
        <Button
          variant="primary"
          tone="brand"
          size="md"
          startIcon={<UserPlus className="w-4 h-4" />}
          onClick={() => setShowInviteModal(true)}
        >
          Send Invitation
        </Button>
      </div>

      <Card className="p-6">
        <h2 className="text-lg font-semibold mb-4">Pending Invitations</h2>
        <div className="text-center py-12 text-gray-500 dark:text-gray-400">
          No pending invitations
        </div>
      </Card>

      <Card className="p-6 bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800">
        <h3 className="font-semibold text-blue-900 dark:text-blue-100 mb-2">How Invitations Work</h3>
        <ul className="space-y-2 text-sm text-blue-800 dark:text-blue-200">
          <li>• Invited users will receive an email with a registration link</li>
          <li>• Invitations expire after 7 days</li>
          <li>• You can resend or cancel invitations at any time</li>
          <li>• New members will have the default "Member" role</li>
        </ul>
      </Card>
    </div>
  )}

  {/* Access Control Tab */}
  {activeTab === 'access' && (
    <div className="space-y-6">
      <Card className="p-6">
        <h2 className="text-lg font-semibold mb-4">Role Permissions</h2>
        <div className="space-y-4">
          <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-semibold text-gray-900 dark:text-white">Owner</h3>
              <Badge variant="light" color="error">Highest Access</Badge>
            </div>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
              Full access to all features including billing, team management, and account settings
            </p>
            <ul className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
              <li>✓ Manage billing and subscriptions</li>
              <li>✓ Invite and remove team members</li>
              <li>✓ Manage all sites and content</li>
              <li>✓ Configure account settings</li>
            </ul>
          </div>

          <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-semibold text-gray-900 dark:text-white">Admin</h3>
              <Badge variant="light" color="primary">High Access</Badge>
            </div>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
              Can manage sites and content, invite team members, but cannot access billing
            </p>
            <ul className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
              <li>✓ Invite team members</li>
              <li>✓ Manage all sites and content</li>
              <li>✓ View usage analytics</li>
              <li>✗ Cannot manage billing</li>
            </ul>
          </div>

          <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-semibold text-gray-900 dark:text-white">Editor</h3>
              <Badge variant="light" color="warning">Medium Access</Badge>
            </div>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
              Can create and edit content, limited settings access
            </p>
            <ul className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
              <li>✓ Create and edit content</li>
              <li>✓ View usage analytics</li>
              <li>✗ Cannot invite users</li>
              <li>✗ Cannot manage billing</li>
            </ul>
          </div>

          <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-semibold text-gray-900 dark:text-white">Viewer</h3>
              <Badge variant="light" color="default">Read-Only</Badge>
            </div>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
              Read-only access to content and analytics
            </p>
            <ul className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
              <li>✓ View content and analytics</li>
              <li>✗ Cannot create or edit</li>
              <li>✗ Cannot invite users</li>
              <li>✗ Cannot manage billing</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  )}

      {/* Invite Modal */}
      {showInviteModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <Card className="p-6 w-full max-w-md">
            <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
              Invite Team Member
            </h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  value={inviteForm.email}
                  onChange={(e) => setInviteForm(prev => ({ ...prev, email: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                  placeholder="user@example.com"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  First Name
                </label>
                <input
                  type="text"
                  value={inviteForm.first_name}
                  onChange={(e) => setInviteForm(prev => ({ ...prev, first_name: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Last Name
                </label>
                <input
                  type="text"
                  value={inviteForm.last_name}
                  onChange={(e) => setInviteForm(prev => ({ ...prev, last_name: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                />
              </div>
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <Button
                variant="secondary"
                onClick={() => {
                  setShowInviteModal(false);
                  setInviteForm({ email: '', first_name: '', last_name: '' });
                }}
                disabled={inviting}
              >
                Cancel
              </Button>
              <Button
                variant="primary"
                onClick={handleInvite}
                disabled={inviting}
              >
                {inviting ? 'Inviting...' : 'Send Invitation'}
              </Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}
