import { useState, useMemo, useEffect, useCallback } from 'react';
import { Button, Card, Col, Form, Input, Modal, Row, Select, Space, Table, Tag, Typography, message, Alert, Dropdown } from 'antd';
import { ArrowLeftOutlined, PlusOutlined, EditOutlined, LockOutlined, UnlockOutlined, StopOutlined, MoreOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';

type UserRole = 'GUEST' | 'MEMBER' | 'LIBRARIAN' | 'ADMINISTRATOR';
type AdminLevel = 'SUPER' | 'STANDARD';

interface UserResponse {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
  role?: UserRole;
  is_active?: boolean;
  phone?: string | null;
  created_at?: string;
  last_login?: string;
}

interface LibraryBranchResponse {
  id: string;
  name: string;
  address?: string;
  phone?: string | null;
  email?: string | null;
  operating_hours?: string | null;
  created_at?: string;
  updated_at?: string;
}

interface LibrarianResponse {
  employee_id: string;
  hire_date: string;
  library_branch_id: string | null;
  id: string;
  user_id: string;
  created_at: string;
  updated_at: string;
}

interface AdministratorResponse {
  admin_level: AdminLevel;
  id: string;
  user_id: string;
  created_at: string;
  updated_at: string;
}

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

export default function UserManagementPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();

  const [users, setUsers] = useState<UserResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>('');
  const [roleFilter, setRoleFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [createLibrarianModalVisible, setCreateLibrarianModalVisible] = useState<boolean>(false);
  const [createAdminModalVisible, setCreateAdminModalVisible] = useState<boolean>(false);
  const [editRoleModalVisible, setEditRoleModalVisible] = useState<boolean>(false);
  const [deactivateConfirmVisible, setDeactivateConfirmVisible] = useState<boolean>(false);
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [branches, setBranches] = useState<LibraryBranchResponse[]>([]);

  const [librarianForm] = Form.useForm();
  const [adminForm] = Form.useForm();
  const [editRoleForm] = Form.useForm();

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const offset = (pagination.current - 1) * pagination.pageSize;
      const queryParams: Record<string, string | number | boolean> = {
        limit: pagination.pageSize,
        offset,
      };
      if (roleFilter) {
        queryParams.role = roleFilter;
      }
      if (statusFilter) {
        queryParams.is_active = statusFilter === 'true';
      }
      const result = await request<UserResponse[]>({
        method: 'GET',
        path: '/auth/users',
        query: queryParams,
      });
      setUsers(result.data);
      setPagination((prev) => ({ ...prev, total: result.data.length }));
    } catch (error) {
      messageApi.error('Failed to load users');
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, roleFilter, statusFilter, messageApi]);

  const fetchBranches = useCallback(async () => {
    try {
      const result = await request<LibraryBranchResponse[]>({
        method: 'GET',
        path: '/library-branches/',
        query: { limit: 100, offset: 0 },
      });
      setBranches(result.data);
    } catch (error) {
      messageApi.error('Failed to load branches');
    }
  }, [messageApi]);

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

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

  const filteredUsers = useMemo(() => {
    if (!searchText) return users;
    const lowerSearch = searchText.toLowerCase();
    return users.filter(
      (u) =>
        u.first_name.toLowerCase().includes(lowerSearch) ||
        u.last_name.toLowerCase().includes(lowerSearch) ||
        u.email.toLowerCase().includes(lowerSearch)
    );
  }, [users, searchText]);

  const selectedUser = useMemo(() => {
    return users.find((u) => u.id === selectedUserId) || null;
  }, [users, selectedUserId]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
  };

  const handleRoleFilterChange = (value: string) => {
    setRoleFilter(value);
  };

  const handleStatusFilterChange = (value: string) => {
    setStatusFilter(value);
  };

  const openCreateLibrarianModal = () => {
    setCreateLibrarianModalVisible(true);
  };

  const closeCreateLibrarianModal = () => {
    setCreateLibrarianModalVisible(false);
    librarianForm.resetFields();
  };

  const openCreateAdminModal = () => {
    setCreateAdminModalVisible(true);
  };

  const closeCreateAdminModal = () => {
    setCreateAdminModalVisible(false);
    adminForm.resetFields();
  };

  const openEditRoleModal = (record: UserResponse) => {
    setSelectedUserId(record.id);
    setEditRoleModalVisible(true);
    editRoleForm.setFieldsValue({ role: record.role });
  };

  const closeEditRoleModal = () => {
    setEditRoleModalVisible(false);
    editRoleForm.resetFields();
  };

  const openDeactivateConfirm = (record: UserResponse) => {
    setSelectedUserId(record.id);
    setDeactivateConfirmVisible(true);
  };

  const closeDeactivateConfirm = () => {
    setDeactivateConfirmVisible(false);
  };

  const handleCreateLibrarian = async () => {
    try {
      const formValues = await librarianForm.validateFields();
      
      const userResult = await request<UserResponse>({
        method: 'POST',
        path: '/auth/users',
        body: {
          email: formValues.email,
          first_name: formValues.first_name,
          last_name: formValues.last_name,
          password: formValues.password,
          role: 'LIBRARIAN',
          is_active: true,
        },
      });

      await request<LibrarianResponse>({
        method: 'POST',
        path: '/auth/librarians',
        body: {
          user_id: userResult.data.id,
          employee_id: formValues.employee_id,
          hire_date: new Date().toISOString().split('T')[0],
          library_branch_id: formValues.library_branch_id || null,
        },
      });

      messageApi.success('Librarian account created successfully');
      setCreateLibrarianModalVisible(false);
      librarianForm.resetFields();
      fetchUsers();
    } catch (error) {
      messageApi.error('Failed to create librarian account');
    }
  };

  const handleCreateAdmin = async () => {
    try {
      const formValues = await adminForm.validateFields();
      
      const userResult = await request<UserResponse>({
        method: 'POST',
        path: '/auth/users',
        body: {
          email: formValues.email,
          first_name: formValues.first_name,
          last_name: formValues.last_name,
          password: formValues.password,
          role: 'ADMINISTRATOR',
          is_active: true,
        },
      });

      await request<AdministratorResponse>({
        method: 'POST',
        path: '/auth/administrators',
        body: {
          user_id: userResult.data.id,
          admin_level: formValues.admin_level,
        },
      });

      messageApi.success('Administrator account created successfully');
      setCreateAdminModalVisible(false);
      adminForm.resetFields();
      fetchUsers();
    } catch (error) {
      messageApi.error('Failed to create administrator account');
    }
  };

  const handleEditRole = async () => {
    try {
      const formValues = await editRoleForm.validateFields();
      
      await request<UserResponse>({
        method: 'PUT',
        path: '/auth/users/{user_id}',
        pathParams: { user_id: selectedUserId! },
        body: { role: formValues.role },
      });

      messageApi.success('User role updated successfully');
      setEditRoleModalVisible(false);
      editRoleForm.resetFields();
      fetchUsers();
    } catch (error) {
      messageApi.error('Failed to update user role');
    }
  };

  const handleResetPassword = async (record: UserResponse) => {
    Modal.confirm({
      title: 'Reset Password',
      content: 'Are you sure you want to reset this user\'s password? A temporary password will be sent to the user.',
      onOk: async () => {
        try {
          await request<UserResponse>({
            method: 'PUT',
            path: '/auth/users/{user_id}',
            pathParams: { user_id: record.id },
            body: { password: 'TempPass123!' },
          });
          messageApi.success('Password has been reset. Temporary password sent to user.');
        } catch (error) {
          messageApi.error('Failed to reset password');
        }
      },
    });
  };

  const handleDeactivateUser = async () => {
    try {
      await request<UserResponse>({
        method: 'PUT',
        path: '/auth/users/{user_id}',
        pathParams: { user_id: selectedUserId! },
        body: { is_active: false },
      });

      messageApi.warning('User account deactivated');
      setDeactivateConfirmVisible(false);
      fetchUsers();
    } catch (error) {
      messageApi.error('Failed to deactivate user');
    }
  };

  const handleUnlockUser = async (record: UserResponse) => {
    try {
      await request<UserResponse>({
        method: 'PUT',
        path: '/auth/users/{user_id}',
        pathParams: { user_id: record.id },
        body: { is_active: true },
      });

      messageApi.success('User account unlocked successfully');
      fetchUsers();
    } catch (error) {
      messageApi.error('Failed to unlock user');
    }
  };

  const navigateToDashboard = () => {
    navigate('/admin/dashboard');
  };

  const columns: ColumnsType<UserResponse> = useMemo(
    () => [
      {
        title: 'User ID',
        dataIndex: 'id',
        key: 'id',
        width: 100,
        ellipsis: true,
      },
      {
        title: 'Full Name',
        key: 'full_name',
        render: (_, record) => `${record.first_name} ${record.last_name}`,
      },
      {
        title: 'Email',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: 'Role',
        dataIndex: 'role',
        key: 'role',
        render: (role: UserRole) => {
          const colorMap: Record<UserRole, string> = {
            ADMINISTRATOR: 'red',
            LIBRARIAN: 'blue',
            MEMBER: 'green',
            GUEST: 'default',
          };
          return <Tag color={colorMap[role] || 'default'}>{role}</Tag>;
        },
      },
      {
        title: 'Status',
        dataIndex: 'is_active',
        key: 'is_active',
        render: (isActive: boolean) => (
          <Tag color={isActive ? 'success' : 'error'}>
            {isActive ? 'Active' : 'Inactive'}
          </Tag>
        ),
      },
      {
        title: 'Created Date',
        dataIndex: 'created_at',
        key: 'created_at',
        render: (date: string) => (date ? new Date(date).toLocaleDateString() : '-'),
      },
      {
        title: 'Last Login',
        dataIndex: 'last_login',
        key: 'last_login',
        render: (date: string) => (date ? new Date(date).toLocaleDateString() : '-'),
        responsive: ['lg'],
      },
      {
        title: 'Actions',
        key: 'actions',
        fixed: 'right',
        width: 200,
        render: (_, record) => (
          <Space size="small">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => openEditRoleModal(record)}
            >
              Edit Role
            </Button>
            <Dropdown
              menu={{
                items: [
                  {
                    key: 'reset',
                    label: 'Reset Password',
                    icon: <LockOutlined />,
                    onClick: () => handleResetPassword(record),
                  },
                  record.is_active
                    ? {
                        key: 'deactivate',
                        label: 'Deactivate',
                        icon: <StopOutlined />,
                        danger: true,
                        onClick: () => openDeactivateConfirm(record),
                      }
                    : {
                        key: 'unlock',
                        label: 'Unlock',
                        icon: <UnlockOutlined />,
                        onClick: () => handleUnlockUser(record),
                      },
                ],
              }}
            >
              <Button type="text" size="small" icon={<MoreOutlined />} />
            </Dropdown>
          </Space>
        ),
      },
    ],
    []
  );

  return (
    <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column' }}>
      {contextHolder}
      <div style={{ minHeight: '100vh', width: '100%', padding: '24px', background: '#f5f5f5' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <Button type="text" icon={<ArrowLeftOutlined />} onClick={navigateToDashboard}>
              Back to Dashboard
            </Button>
            <Typography.Title level={2} style={{ margin: 0 }}>
              User Management
            </Typography.Title>
          </div>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={openCreateLibrarianModal}>
              Create Librarian
            </Button>
            <Button type="primary" ghost icon={<PlusOutlined />} onClick={openCreateAdminModal}>
              Create Administrator
            </Button>
          </Space>
        </div>

        <Card bordered={false} style={{ marginBottom: '16px' }}>
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} sm={12} md={8}>
              <Input.Search
                placeholder="Search by name or email..."
                allowClear
                value={searchText}
                onChange={handleSearchChange}
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Select
                placeholder="Filter by Role"
                allowClear
                style={{ width: '100%' }}
                value={roleFilter || undefined}
                onChange={handleRoleFilterChange}
                options={[
                  { label: 'All Roles', value: '' },
                  { label: 'Member', value: 'MEMBER' },
                  { label: 'Librarian', value: 'LIBRARIAN' },
                  { label: 'Administrator', value: 'ADMINISTRATOR' },
                ]}
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Select
                placeholder="Filter by Status"
                allowClear
                style={{ width: '100%' }}
                value={statusFilter || undefined}
                onChange={handleStatusFilterChange}
                options={[
                  { label: 'All Statuses', value: '' },
                  { label: 'Active', value: 'true' },
                  { label: 'Inactive', value: 'false' },
                ]}
              />
            </Col>
          </Row>
        </Card>

        <Card bordered={false}>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={filteredUsers}
            loading={loading}
            pagination={pagination}
            onChange={(newPagination) => {
              setPagination({
                current: newPagination.current || 1,
                pageSize: newPagination.pageSize || 20,
                total: newPagination.total || 0,
              });
            }}
            scroll={{ x: 1200 }}
          />
        </Card>
      </div>

      <Modal
        title="Create Librarian Account"
        open={createLibrarianModalVisible}
        onOk={handleCreateLibrarian}
        onCancel={closeCreateLibrarianModal}
        width={600}
        okText="Create Librarian"
        cancelText="Cancel"
      >
        <Form form={librarianForm} layout="vertical">
          <Form.Item
            name="first_name"
            label="First Name"
            rules={[{ required: true, message: 'First name is required' }]}
          >
            <Input placeholder="Enter first name" />
          </Form.Item>
          <Form.Item
            name="last_name"
            label="Last Name"
            rules={[{ required: true, message: 'Last name is required' }]}
          >
            <Input placeholder="Enter last name" />
          </Form.Item>
          <Form.Item
            name="email"
            label="Email"
            rules={[
              { required: true, type: 'email', message: 'Valid email is required' },
            ]}
          >
            <Input placeholder="Enter email address" />
          </Form.Item>
          <Form.Item
            name="employee_id"
            label="Employee ID"
            rules={[{ required: true, message: 'Employee ID is required' }]}
          >
            <Input placeholder="Enter employee ID" />
          </Form.Item>
          <Form.Item name="library_branch_id" label="Assigned Branch">
            <Select
              placeholder="Select branch"
              allowClear
              style={{ width: '100%' }}
              options={branches.map((b) => ({ label: b.name, value: b.id }))}
            />
          </Form.Item>
          <Form.Item
            name="password"
            label="Temporary Password"
            rules={[
              { required: true, message: 'Password is required' },
              { min: 8, message: 'Password must be at least 8 characters' },
            ]}
          >
            <Input.Password placeholder="Enter temporary password" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Create Administrator Account"
        open={createAdminModalVisible}
        onOk={handleCreateAdmin}
        onCancel={closeCreateAdminModal}
        width={600}
        okText="Create Administrator"
        cancelText="Cancel"
      >
        <Form form={adminForm} layout="vertical">
          <Form.Item
            name="first_name"
            label="First Name"
            rules={[{ required: true, message: 'First name is required' }]}
          >
            <Input placeholder="Enter first name" />
          </Form.Item>
          <Form.Item
            name="last_name"
            label="Last Name"
            rules={[{ required: true, message: 'Last name is required' }]}
          >
            <Input placeholder="Enter last name" />
          </Form.Item>
          <Form.Item
            name="email"
            label="Email"
            rules={[
              { required: true, type: 'email', message: 'Valid email is required' },
            ]}
          >
            <Input placeholder="Enter email address" />
          </Form.Item>
          <Form.Item
            name="admin_level"
            label="Admin Level"
            rules={[{ required: true, message: 'Admin level is required' }]}
          >
            <Select
              placeholder="Select admin level"
              style={{ width: '100%' }}
              options={[
                { label: 'Standard', value: 'STANDARD' },
                { label: 'Super', value: 'SUPER' },
              ]}
            />
          </Form.Item>
          <Form.Item
            name="password"
            label="Temporary Password"
            rules={[
              { required: true, message: 'Password is required' },
              { min: 8, message: 'Password must be at least 8 characters' },
            ]}
          >
            <Input.Password placeholder="Enter temporary password" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit User Role"
        open={editRoleModalVisible}
        onOk={handleEditRole}
        onCancel={closeEditRoleModal}
        width={480}
        okText="Update Role"
        cancelText="Cancel"
      >
        <Form form={editRoleForm} layout="vertical">
          <Alert
            message="Changing a user's role will immediately affect their permissions. Please confirm this action."
            type="warning"
            showIcon
            style={{ marginBottom: '16px' }}
          />
          <Form.Item
            name="role"
            label="New Role"
            rules={[{ required: true, message: 'Please select a role' }]}
          >
            <Select
              placeholder="Select new role"
              style={{ width: '100%' }}
              options={[
                { label: 'Member', value: 'MEMBER' },
                { label: 'Librarian', value: 'LIBRARIAN' },
                { label: 'Administrator', value: 'ADMINISTRATOR' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Confirm Account Deactivation"
        open={deactivateConfirmVisible}
        onOk={handleDeactivateUser}
        onCancel={closeDeactivateConfirm}
        width={440}
        okText="Deactivate"
        okButtonProps={{ danger: true }}
        cancelText="Cancel"
      >
        <Typography.Paragraph>
          Are you sure you want to deactivate this user account? The user will no longer be able to log in or access the system. This action can be reversed by reactivating the account.
        </Typography.Paragraph>
      </Modal>
    </div>
  );
}