import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useUser, useUpdateUser, useResetUserPassword } from '../../hooks/useUsers';
import {
  useClients,
  useTeamsForClient,
  useAssignPMAny,
  useRemovePMAny,
  useAddTeamMemberAny,
  useRemoveTeamMemberAny,
} from '../../hooks/useClients';
import { useToastContext } from '../../contexts/ToastContext';
import { useQueryClient } from '@tanstack/react-query';
import type { UserRole, UpdateUserRequest, User, Client, Team } from '../../types/api';

export function UserDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const toast = useToastContext();

  const { data: user, isLoading, error } = useUser(id!);
  const updateUserMutation = useUpdateUser();
  const resetPasswordMutation = useResetUserPassword();

  const [formData, setFormData] = useState<UpdateUserRequest>({
    email: '',
    full_name: '',
    role: 'client' as UserRole,
    is_active: true,
  });

  useEffect(() => {
    if (user) {
      setFormData({
        email: user.email,
        full_name: user.full_name,
        role: user.role,
        is_active: user.is_active,
      });
    }
  }, [user]);

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/4 mb-8"></div>
          <div className="space-y-4">
            <div className="h-12 bg-gray-200 rounded"></div>
            <div className="h-12 bg-gray-200 rounded"></div>
            <div className="h-12 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !user) {
    return (
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">User Not Found</h1>
        <div className="bg-red-50 border border-red-200 rounded-md p-4">
          <p className="text-red-600">Failed to load user details.</p>
        </div>
        <Link
          to="/admin/users"
          className="mt-4 inline-flex items-center text-blue-600 hover:text-blue-800"
        >
          ← Back to Users
        </Link>
      </div>
    );
  }

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

    try {
      await updateUserMutation.mutateAsync({
        userId: id!,
        data: formData,
      });
      toast.toastOnly.success('User updated successfully');
      navigate('/admin/users');
    } catch (error) {
      const errorMessage = error instanceof Error && 'response' in error
        ? (error as { response?: { data?: { detail?: string } } }).response?.data?.detail
        : undefined;
      toast.toastOnly.error(errorMessage || 'Failed to update user');
    }
  };

  const handleResetPassword = async () => {
    if (!window.confirm(`Are you sure you want to reset password for ${user.email}?`)) {
      return;
    }

    try {
      const response = await resetPasswordMutation.mutateAsync(id!);
      toast.toastOnly.success(`Password reset. Temporary password: ${response.temporary_password}`);
    } catch (error) {
      const errorMessage = error instanceof Error && 'response' in error
        ? (error as { response?: { data?: { detail?: string } } }).response?.data?.detail
        : undefined;
      toast.toastOnly.error(errorMessage || 'Failed to reset password');
    }
  };

  const hasChanges =
    formData.email !== user.email ||
    formData.full_name !== user.full_name ||
    formData.role !== user.role ||
    formData.is_active !== user.is_active;

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-6">
        <Link
          to="/admin/users"
          className="inline-flex items-center text-blue-600 hover:text-blue-800 mb-4"
        >
          <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
          Back to Users
        </Link>
        <h1 className="text-3xl font-bold text-gray-900">Edit User</h1>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Form */}
        <div className="lg:col-span-2">
          <form onSubmit={handleSubmit} className="bg-white shadow rounded-lg p-6 space-y-6">
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
                Email
              </label>
              <input
                type="email"
                id="email"
                required
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            <div>
              <label htmlFor="full_name" className="block text-sm font-medium text-gray-700 mb-1">
                Full Name
              </label>
              <input
                type="text"
                id="full_name"
                required
                value={formData.full_name}
                onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            <div>
              <label htmlFor="role" className="block text-sm font-medium text-gray-700 mb-1">
                Role
              </label>
              <select
                id="role"
                required
                value={formData.role}
                onChange={(e) => setFormData({ ...formData, role: e.target.value as UserRole })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="reviewer">Reviewer</option>
                <option value="linguist">Linguist</option>
                <option value="production">Production</option>
                <option value="project_manager">Project Manager</option>
                <option value="admin">Admin</option>
              </select>
            </div>

            <div className="flex items-center">
              <input
                type="checkbox"
                id="is_active"
                checked={formData.is_active}
                onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <label htmlFor="is_active" className="ml-2 block text-sm text-gray-700">
                Active User
              </label>
            </div>

            <div className="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200">
              <button
                type="button"
                onClick={() => navigate('/admin/users')}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={!hasChanges || updateUserMutation.isPending}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {updateUserMutation.isPending ? 'Saving...' : 'Save Changes'}
              </button>
            </div>
          </form>
        </div>

        {/* Sidebar */}
        <div className="lg:col-span-1 space-y-6">
          {/* User Info Card */}
          <div className="bg-white shadow rounded-lg p-6">
            <h3 className="text-lg font-medium text-gray-900 mb-4">User Information</h3>
            <dl className="space-y-3">
              <div>
                <dt className="text-sm font-medium text-gray-500">User ID</dt>
                <dd className="mt-1 text-sm text-gray-900 font-mono">{user.id}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Authentication Method</dt>
                <dd className="mt-1">
                  <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize ${
                    user.auth_provider === 'microsoft' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'
                  }`}>
                    {user.auth_provider === 'microsoft' && (
                      <svg className="w-3 h-3 mr-1" viewBox="0 0 21 21" fill="currentColor">
                        <rect x="1" y="1" width="9" height="9"/>
                      </svg>
                    )}
                    {user.auth_provider}
                  </span>
                </dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Created</dt>
                <dd className="mt-1 text-sm text-gray-900">
                  {user.created_at ? new Date(user.created_at).toLocaleString() : 'N/A'}
                </dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Status</dt>
                <dd className="mt-1">
                  <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                    user.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                  }`}>
                    {user.is_active ? 'Active' : 'Inactive'}
                  </span>
                </dd>
              </div>
            </dl>
          </div>

          {/* Assignments Card */}
          <UserAssignmentsPanel user={user} />

          {/* Actions Card */}
          <div className="bg-white shadow rounded-lg p-6">
            <h3 className="text-lg font-medium text-gray-900 mb-4">Actions</h3>
            <div className="space-y-3">
              {user.auth_provider === 'local' ? (
                <>
                  <button
                    onClick={handleResetPassword}
                    disabled={resetPasswordMutation.isPending}
                    className="w-full flex items-center justify-center px-4 py-2 text-sm font-medium text-orange-700 bg-orange-50 border border-orange-200 rounded-lg hover:bg-orange-100 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
                    </svg>
                    {resetPasswordMutation.isPending ? 'Resetting...' : 'Reset Password'}
                  </button>

                  <div className="pt-3 border-t border-gray-200">
                    <p className="text-xs text-gray-500">
                      Note: Resetting a password will generate a temporary password that must be shared with the user securely.
                    </p>
                  </div>
                </>
              ) : (
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="flex items-start">
                    <svg className="w-5 h-5 text-blue-600 mt-0.5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div>
                      <p className="text-sm font-medium text-blue-800">Microsoft Authentication</p>
                      <p className="text-xs text-blue-700 mt-1">
                        This user authenticates via Microsoft. Password management is handled by Microsoft Azure AD.
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function UserAssignmentsPanel({ user }: { user: User }) {
  const qc = useQueryClient();
  const toast = useToastContext();
  const { data: clients = [], isLoading: clientsLoading } = useClients();
  const [selectedClientId, setSelectedClientId] = useState<string | null>(null);
  const { data: teams = [], isLoading: teamsLoading } = useTeamsForClient(selectedClientId);

  const assignPM = useAssignPMAny();
  const removePM = useRemovePMAny();
  const addMember = useAddTeamMemberAny();
  const removeMember = useRemoveTeamMemberAny();

  const refreshUser = () => qc.invalidateQueries({ queryKey: ['users', user.id] });

  if (clientsLoading) {
    return (
      <div className="bg-white shadow rounded-lg p-6">
        <div className="animate-pulse h-4 bg-gray-200 rounded w-1/2"></div>
      </div>
    );
  }

  if (clients.length === 0) return null;

  if (user.role === 'project_manager') {
    return (
      <PMAssignmentsCard
        user={user}
        clients={clients}
        assignPM={assignPM}
        removePM={removePM}
        refreshUser={refreshUser}
        toast={toast}
      />
    );
  }

  return (
    <TeamMembershipsCard
      user={user}
      clients={clients}
      selectedClientId={selectedClientId}
      setSelectedClientId={setSelectedClientId}
      teams={teams}
      teamsLoading={teamsLoading}
      addMember={addMember}
      removeMember={removeMember}
      toast={toast}
    />
  );
}

function PMAssignmentsCard({
  user,
  clients,
  assignPM,
  removePM,
  refreshUser,
  toast,
}: {
  user: User;
  clients: Client[];
  assignPM: ReturnType<typeof useAssignPMAny>;
  removePM: ReturnType<typeof useRemovePMAny>;
  refreshUser: () => void;
  toast: ReturnType<typeof useToastContext>;
}) {
  const pmClientIds = user.pm_client_ids ?? [];

  const handleToggle = async (clientId: string, isAssigned: boolean) => {
    try {
      if (isAssigned) {
        await removePM.mutateAsync({ clientId, userId: user.id });
        toast.toastOnly.success('Removed as PM from client');
      } else {
        await assignPM.mutateAsync({ clientId, userId: user.id });
        toast.toastOnly.success('Assigned as PM to client');
      }
      refreshUser();
    } catch {
      toast.toastOnly.error('Failed to update PM assignment');
    }
  };

  const isBusy = assignPM.isPending || removePM.isPending;

  return (
    <div className="bg-white shadow rounded-lg p-6">
      <h3 className="text-lg font-medium text-gray-900 mb-4">PM Client Assignments</h3>
      {clients.length === 0 ? (
        <p className="text-sm text-gray-500">No clients found.</p>
      ) : (
        <ul className="divide-y divide-gray-100">
          {clients.map((client) => {
            const isAssigned = pmClientIds.includes(client.id);
            return (
              <li key={client.id} className="flex items-center justify-between py-2">
                <div>
                  <span className="text-sm font-medium text-gray-900">{client.name}</span>
                  {!client.is_active && (
                    <span className="ml-2 text-xs text-gray-400">(inactive)</span>
                  )}
                </div>
                <button
                  onClick={() => handleToggle(client.id, isAssigned)}
                  disabled={isBusy}
                  className={`px-3 py-1 text-xs font-medium rounded-full border transition-colors disabled:opacity-50 ${
                    isAssigned
                      ? 'bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100'
                      : 'bg-gray-50 text-gray-600 border-gray-200 hover:bg-gray-100'
                  }`}
                >
                  {isAssigned ? 'Assigned ✓' : 'Assign'}
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

function TeamMembershipsCard({
  user,
  clients,
  selectedClientId,
  setSelectedClientId,
  teams,
  teamsLoading,
  addMember,
  removeMember,
  toast,
}: {
  user: User;
  clients: Client[];
  selectedClientId: string | null;
  setSelectedClientId: (id: string | null) => void;
  teams: Team[];
  teamsLoading: boolean;
  addMember: ReturnType<typeof useAddTeamMemberAny>;
  removeMember: ReturnType<typeof useRemoveTeamMemberAny>;
  toast: ReturnType<typeof useToastContext>;
}) {
  const handleToggle = async (team: Team, isMember: boolean) => {
    if (!selectedClientId) return;
    try {
      if (isMember) {
        await removeMember.mutateAsync({ clientId: selectedClientId, teamId: team.id, userId: user.id });
        toast.toastOnly.success(`Removed from team "${team.name}"`);
      } else {
        await addMember.mutateAsync({ clientId: selectedClientId, teamId: team.id, userId: user.id });
        toast.toastOnly.success(`Added to team "${team.name}"`);
      }
    } catch {
      toast.toastOnly.error('Failed to update team membership');
    }
  };

  const isBusy = addMember.isPending || removeMember.isPending;

  return (
    <div className="bg-white shadow rounded-lg p-6">
      <h3 className="text-lg font-medium text-gray-900 mb-4">Team Memberships</h3>
      <div className="mb-4">
        <label className="block text-sm font-medium text-gray-700 mb-1">Select Client</label>
        <select
          value={selectedClientId ?? ''}
          onChange={(e) => setSelectedClientId(e.target.value || null)}
          className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">— pick a client —</option>
          {clients.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </div>

      {selectedClientId && (
        <>
          {teamsLoading ? (
            <div className="animate-pulse space-y-2">
              <div className="h-4 bg-gray-200 rounded w-3/4"></div>
              <div className="h-4 bg-gray-200 rounded w-1/2"></div>
            </div>
          ) : teams.length === 0 ? (
            <p className="text-sm text-gray-500">No teams for this client.</p>
          ) : (
            <ul className="divide-y divide-gray-100">
              {teams.map((team) => {
                const isMember = team.member_user_ids.includes(user.id);
                return (
                  <li key={team.id} className="flex items-center justify-between py-2">
                    <span className="text-sm font-medium text-gray-900">{team.name}</span>
                    <button
                      onClick={() => handleToggle(team, isMember)}
                      disabled={isBusy}
                      className={`px-3 py-1 text-xs font-medium rounded-full border transition-colors disabled:opacity-50 ${
                        isMember
                          ? 'bg-teal-50 text-teal-700 border-teal-200 hover:bg-teal-100'
                          : 'bg-gray-50 text-gray-600 border-gray-200 hover:bg-gray-100'
                      }`}
                    >
                      {isMember ? 'Member ✓' : 'Add'}
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
        </>
      )}
    </div>
  );
}
