import { useMemo, useState } from 'react';

import { useOrgUsers } from '../../hooks/useUsers';
import { useLanguage } from '../../providers/language/LanguageContext';

import type { 
  MitgliederLogicReturn, 
  UserActionConfig,
  UserColumnConfig 
} from './mitgliederTypes';

export function useMitgliederLogic(): MitgliederLogicReturn {
  const { users, loading, error, refetch, updateUser, deleteUser, createUser } = useOrgUsers();
  const { t } = useLanguage();
  const [editingUser, setEditingUser] = useState<any>(null);
  const [deletingUser, setDeletingUser] = useState<any>(null);

  // Configure columns for the users table
  const columns: UserColumnConfig[] = useMemo(() => [
    {
      key: 'username',
      label: t('users.column.username', 'Username'),
      type: 'string',
      width: 150,
      minWidth: 120,
      maxWidth: 200,
      sortable: true,
      filterable: true,
      searchable: true,
      formatter: (value: string | undefined) => (
        <span className="userName">
          {value || t('users.noUsername', 'No Username')}
        </span>
      )
    },
    {
      key: 'fullName',
      label: t('users.column.name', 'Name'),
      type: 'string',
      width: 200,
      minWidth: 150,
      maxWidth: 300,
      sortable: true,
      filterable: true,
      searchable: true,
      formatter: (value: string | undefined) => (
        <span className="userFullName">
          {value || t('users.noName', 'No Name')}
        </span>
      )
    },
    {
      key: 'email',
      label: t('users.column.email', 'Email'),
      type: 'string',
      width: 250,
      minWidth: 200,
      maxWidth: 350,
      sortable: true,
      filterable: true,
      searchable: true,
      formatter: (value: string | undefined) => (
        <span className="userEmail">
          {value || t('users.noEmail', 'No Email')}
        </span>
      )
    },
    {
      key: 'language',
      label: t('users.column.language', 'Language'),
      type: 'enum',
      width: 120,
      minWidth: 100,
      maxWidth: 150,
      sortable: true,
      filterable: true,
      filterOptions: ['en', 'de', 'fr'],
      formatter: (value: string | undefined) => {
        const languageMap: Record<string, string> = {
          'en': t('language.english', 'English'),
          'de': t('language.german', 'Deutsch'),
          'fr': t('language.french', 'Français')
        };
        return (
          <span className="userLanguage">
            {value ? languageMap[value] || value : t('users.noLanguage', 'No Language')}
          </span>
        );
      }
    },
    {
      key: 'privilege',
      label: t('users.column.privilege', 'Privilege'),
      type: 'enum',
      width: 120,
      minWidth: 100,
      maxWidth: 150,
      sortable: true,
      filterable: true,
      filterOptions: ['viewer', 'user', 'admin', 'sysadmin'],
      formatter: (value: string | undefined) => {
        const privilegeMap: Record<string, string> = {
          'viewer': t('users.privilege.viewer', 'Viewer'),
          'user': t('users.privilege.user', 'User'),
          'admin': t('users.privilege.admin', 'Admin'),
          'sysadmin': t('users.privilege.sysadmin', 'Sysadmin')
        };
        return (
          <span className="userPrivilege">
            {value ? privilegeMap[value] || value : t('users.noPrivilege', 'No Privilege')}
          </span>
        );
      }
    },
    {
      key: 'enabled',
      label: t('users.column.enabled', 'Enabled'),
      type: 'boolean',
      width: 100,
      minWidth: 80,
      maxWidth: 120,
      sortable: true,
      filterable: true,
      formatter: (value: boolean | undefined) => (
        <span className={`userEnabled ${value ? 'enabled' : 'disabled'}`}>
          {value ? t('users.enabled.yes', 'Yes') : t('users.enabled.no', 'No')}
        </span>
      )
    },
    {
      key: 'authenticationAuthority',
      label: t('users.column.authAuthority', 'Auth Authority'),
      type: 'enum',
      width: 150,
      minWidth: 120,
      maxWidth: 200,
      sortable: true,
      filterable: true,
      filterOptions: ['local', 'msft'],
      formatter: (value: string | undefined) => {
        const authMap: Record<string, string> = {
          'local': t('users.auth.local', 'Local'),
          'msft': t('users.auth.msft', 'Microsoft')
        };
        return (
          <span className="userAuthAuthority">
            {value ? authMap[value] || value : t('users.noAuthAuthority', 'No Auth Authority')}
          </span>
        );
      }
    }
  ], [t]);

  // Handle edit user
  const handleEditUser = (user: any) => {
    setEditingUser(user);
  };

  // Handle save user
  const handleSaveUser = async (updatedUser: any) => {
    try {
      await updateUser(updatedUser.id, updatedUser);
      setEditingUser(null);
    } catch (error) {
      console.error('Failed to update user:', error);
    }
  };

  // Handle cancel edit
  const handleCancelEdit = () => {
    setEditingUser(null);
  };

  // Handle delete user
  const handleDeleteUser = (user: any) => {
    setDeletingUser(user);
  };

  // Handle confirm delete
  const handleConfirmDelete = async () => {
    if (deletingUser) {
      try {
        await deleteUser(deletingUser.id);
        setDeletingUser(null);
      } catch (error) {
        console.error('Failed to delete user:', error);
      }
    }
  };

  // Handle cancel delete
  const handleCancelDelete = () => {
    setDeletingUser(null);
  };

  // Handle save new user
  const handleSaveNewUser = async (userData: any) => {
    try {
      // Create user data with required fields
      const newUserData = {
        username: userData.username,
        email: userData.email,
        password: userData.password,
        fullName: userData.fullName,
        language: userData.language,
        enabled: userData.enabled || false,
        privilege: userData.privilege,
        authenticationAuthority: 'local' // New users are always local
      };
      
      // Debug logging
      console.log('Creating user with data:', newUserData);
      console.log('Password field:', userData.password);
      console.log('Password type:', typeof userData.password);
      console.log('Password length:', userData.password?.length);
      
      await createUser(newUserData);
    } catch (error) {
      console.error('Failed to create user:', error);
    }
  };

  // Handle cancel add user
  const handleCancelAddUser = () => {
    // This will be handled by the parent component
  };

  // Configure action buttons
  const actions: UserActionConfig[] = useMemo(() => [
    {
      type: 'edit',
      title: t('users.actions.edit', 'Edit'),
      onAction: (row: any) => handleEditUser(row)
    },
    {
      type: 'delete',
      title: t('users.actions.delete', 'Delete'),
      onAction: (row: any) => handleDeleteUser(row)
    }
  ] as any, [t]);

  return {
    // Data
    users,
    loading,
    error,
    
    // Refetch function
    refetch,
    
    // Additional data for rendering
    columns,
    actions,
    
    // Edit functionality
    editingUser,
    setEditingUser,
    handleSaveUser,
    handleCancelEdit,
    
    // Delete functionality
    deletingUser,
    setDeletingUser,
    handleConfirmDelete,
    handleCancelDelete,
    
    // Add user functionality
    handleSaveNewUser,
    handleCancelAddUser
  };
}
