import { useEffect, useMemo, useState } from 'react';
import {
  Alert,
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Statistic,
  Descriptions,
  Switch,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { request } from '@/request';

const { Text } = Typography;

export default function UserManagementSettings() {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [branches, setBranches] = useState([]);
  const [permissionCatalog, setPermissionCatalog] = useState([]);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  const [onboarding, setOnboarding] = useState(null);
  const [sessionModal, setSessionModal] = useState({ open: false, user: null, items: [], loading: false });
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const load = async () => {
    setLoading(true);
    const [userRes, roleRes, branchRes, permissionRes] = await Promise.all([
      request.get({ entity: 'admin-access/users' }),
      request.list({ entity: 'role', options: { page: 1, items: 100 } }),
      request.list({ entity: 'branch', options: { page: 1, items: 100 } }),
      request.get({ entity: 'permission/catalog' }),
    ]);
    setUsers(userRes?.result || []);
    setRoles(roleRes?.result || []);
    setBranches(branchRes?.result || []);
    setPermissionCatalog(permissionRes?.result || []);
    setLoading(false);
  };

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

  const roleOptions = useMemo(() => roles.map((role) => ({ value: role._id, label: role.name })), [roles]);
  const branchOptions = useMemo(() => branches.map((branch) => ({ value: branch._id, label: branch.name })), [branches]);

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ enabled: true, branches: [], roleRefs: [] });
    setOpen(true);
  };

  const openEdit = (record) => {
    setEditing(record);
    form.setFieldsValue({
      name: record.name,
      surname: record.surname,
      email: record.email,
      phone: record.phone,
      enabled: record.enabled !== false,
      roleRefs: (record.roleRefs || []).map((role) => role?._id || role),
      branches: (record.branches || []).map((branch) => branch?._id || branch),
      permissions: record.permissions || record.directPermissions || [],
    });
    setOpen(true);
  };

  const save = async () => {
    const values = await form.validateFields();
    const response = editing
      ? await request.patch({ entity: `admin-access/users/${editing._id}`, jsonData: values })
      : await request.post({ entity: 'admin-access/users', jsonData: values });
    if (response?.success) {
      message.success(editing ? 'User updated' : 'User created');
      setOpen(false);
      if (!editing && response?.result) {
        setOnboarding({
          name: [response.result?.name, response.result?.surname].filter(Boolean).join(' ') || response.result?.email,
          email: response.result?.email,
          temporaryPassword: response.result?.temporaryPassword,
          setupLink: response.result?.setupLink,
        });
      }
      load();
    }
  };

  const resetPassword = async (record) => {
    const response = await request.post({ entity: `admin-access/users/${record._id}/reset-password`, jsonData: {} });
    if (response?.success) {
      message.success('Password setup package refreshed');
      setOnboarding({
        name: [record?.name, record?.surname].filter(Boolean).join(' ') || record?.email,
        email: record?.email,
        temporaryPassword: response.result?.temporaryPassword,
        setupLink: response.result?.setupLink,
      });
    }
  };

  const openSessions = async (record) => {
    setSessionModal({ open: true, user: record, items: [], loading: true });
    const response = await request.get({ entity: `admin-access/users/${record._id}/sessions` });
    setSessionModal({
      open: true,
      user: record,
      items: response?.result?.sessions || [],
      loading: false,
    });
  };

  const revokeSession = async (record, sessionId) => {
    const response = await request.delete({ entity: `admin-access/users/${record._id}/sessions/${sessionId}` });
    if (response?.success) {
      message.success('Session revoked');
      setSessionModal((current) => ({ ...current, items: response?.result?.sessions || [] }));
    }
  };

  const revokeAllSessions = async (record) => {
    const response = await request.delete({ entity: `admin-access/users/${record._id}/sessions` });
    if (response?.success) {
      message.success('All sessions revoked');
      setSessionModal((current) => ({ ...current, items: [] }));
    }
  };

  return (
    <Space direction="vertical" size={16} style={{ width: '100%' }}>
      <Alert
        type="info"
        showIcon
        message="Use User Management for daily team administration. Access Control remains the deeper RBAC console."
      />
      <Card size="small">
        <Space wrap>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            Add User
          </Button>
          <Button>
            <Link to="/settings/edit/access_control">Set Roles & Access Rules</Link>
          </Button>
        </Space>
      </Card>
      <Space style={{ width: '100%', justifyContent: 'space-between' }}>
        <div>
          <Text strong>User Management</Text>
          <div>
            <Text type="secondary">Create users, assign roles and branches, and review recent access activity.</Text>
          </div>
        </div>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={load}>
            Refresh
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            New User
          </Button>
        </Space>
      </Space>

      <Table
        rowKey="_id"
        dataSource={users}
        loading={loading}
        pagination={{ pageSize: 8 }}
        columns={[
          {
            title: 'User',
            render: (_, record) => (
              <Space direction="vertical" size={0}>
                <Text strong>{record.name || 'Unnamed user'}</Text>
                <Text type="secondary">{record.email}</Text>
              </Space>
            ),
          },
          {
            title: 'Roles',
            render: (_, record) => (
              <Space wrap>
                {(record.roleRefs || []).slice(0, 3).map((role) => (
                  <Tag key={role?._id || role}>{role?.name || role}</Tag>
                ))}
              </Space>
            ),
          },
          {
            title: 'Direct Permissions',
            render: (_, record) => {
              const permissions = record.permissions || record.directPermissions || [];
              return permissions.length ? (
                <Tag color="blue">{permissions.length} direct</Tag>
              ) : (
                <Text type="secondary">Role-only</Text>
              );
            },
          },
          {
            title: 'Branches',
            render: (_, record) => (
              <Space wrap>
                {(record.branches || []).length ? (
                  (record.branches || []).map((branch) => <Tag key={branch?._id || branch}>{branch?.name || branch}</Tag>)
                ) : (
                  <Text type="secondary">All / unscoped</Text>
                )}
              </Space>
            ),
          },
          {
            title: 'Status',
            render: (_, record) => (
              <Space wrap>
                <Tag color={record.enabled !== false ? 'green' : 'red'}>{record.enabled !== false ? 'Enabled' : 'Disabled'}</Tag>
                {!record.lastLoginAt && record.enabled !== false ? <Tag color="gold">Pending setup</Tag> : null}
              </Space>
            ),
          },
          {
            title: 'Last Login',
            render: (_, record) => (record.lastLoginAt ? new Date(record.lastLoginAt).toLocaleString() : <Text type="secondary">Never</Text>),
          },
          {
            title: 'Actions',
            render: (_, record) => (
              <Space>
                <Button size="small" onClick={() => openEdit(record)}>
                  Edit
                </Button>
                <Button size="small" onClick={() => openSessions(record)}>
                  Sessions
                </Button>
                <Button size="small" onClick={() => resetPassword(record)}>
                  Reset Password
                </Button>
              </Space>
            ),
          },
        ]}
      />

      <Drawer
        title={editing ? 'Edit User' : 'Create User'}
        open={open}
        width={520}
        onClose={() => setOpen(false)}
        extra={
          <Space>
            <Button onClick={() => setOpen(false)}>Cancel</Button>
            <Button type="primary" onClick={save}>
              Save
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="First Name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="surname" label="Surname">
            <Input />
          </Form.Item>
          <Form.Item name="email" label="Email" rules={[{ required: true, type: 'email' }]}>
            <Input disabled={Boolean(editing)} />
          </Form.Item>
          <Form.Item name="phone" label="Phone">
            <Input />
          </Form.Item>
          <Form.Item name="roleRefs" label="Roles">
            <Select mode="multiple" options={roleOptions} />
          </Form.Item>
          <Form.Item name="permissions" label="Direct Permissions">
            <Select
              mode="multiple"
              showSearch
              optionFilterProp="label"
              options={permissionCatalog.map((permission) => ({
                value: permission.key,
                label: `${permission.key}${permission.description ? ` - ${permission.description}` : ''}`,
              }))}
              placeholder="Add direct permissions only when roles are not enough"
            />
          </Form.Item>
          <Form.Item name="branches" label="Branch Access">
            <Select mode="multiple" options={branchOptions} />
          </Form.Item>
          <Form.Item name="enabled" label="Enabled" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Drawer>

      <Modal
        title="User Setup Package"
        open={Boolean(onboarding)}
        footer={<Button type="primary" onClick={() => setOnboarding(null)}>Done</Button>}
        onCancel={() => setOnboarding(null)}
      >
        <Space direction="vertical" size={14} style={{ width: '100%' }}>
          <Alert
            type="success"
            showIcon
            message={`${onboarding?.name || 'User'} is ready for first-time access`}
            description="Send the setup link to the user so they can set their own password from the existing reset-password screen."
          />
          <div>
            <Text strong>Email</Text>
            <Typography.Paragraph copyable={{ text: onboarding?.email || '' }} style={{ marginBottom: 0 }}>
              {onboarding?.email || '-'}
            </Typography.Paragraph>
          </div>
          <div>
            <Text strong>Temporary password</Text>
            <Typography.Paragraph copyable={{ text: onboarding?.temporaryPassword || '' }} style={{ marginBottom: 0 }}>
              {onboarding?.temporaryPassword || '-'}
            </Typography.Paragraph>
          </div>
          <div>
            <Text strong>Setup link</Text>
            <Typography.Paragraph copyable={{ text: onboarding?.setupLink || '' }} style={{ marginBottom: 0, wordBreak: 'break-all' }}>
              {onboarding?.setupLink || '-'}
            </Typography.Paragraph>
          </div>
        </Space>
      </Modal>

      <Modal
        title={sessionModal.user ? `Sessions - ${sessionModal.user.name || sessionModal.user.email}` : 'Sessions'}
        open={sessionModal.open}
        width={760}
        footer={<Button onClick={() => setSessionModal({ open: false, user: null, items: [], loading: false })}>Close</Button>}
        onCancel={() => setSessionModal({ open: false, user: null, items: [], loading: false })}
      >
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          <Alert
            type="info"
            showIcon
            message="Revoke sessions when a device is lost, a role changes, or you need to force a re-login immediately."
          />
          <Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
            <Statistic title="Active sessions" value={sessionModal.items.filter((item) => item.active).length} />
            <Statistic title="Total tracked sessions" value={sessionModal.items.length} />
            {sessionModal.user ? (
              <Popconfirm
                title="Revoke all sessions?"
                description="This user will need to sign in again on every device."
                onConfirm={() => revokeAllSessions(sessionModal.user)}
              >
                <Button danger>Revoke All Sessions</Button>
              </Popconfirm>
            ) : null}
          </Space>
          <Table
            rowKey="id"
            loading={sessionModal.loading}
            dataSource={sessionModal.items}
            pagination={false}
            locale={{ emptyText: 'No active sessions recorded for this user.' }}
            columns={[
              {
                title: 'Session',
                render: (_, item) => (
                  <Descriptions size="small" column={1} items={[
                    { key: 'token', label: 'Token', children: item.tokenPreview },
                    { key: 'issued', label: 'Issued', children: item.issuedAt ? new Date(item.issuedAt).toLocaleString() : 'Unknown' },
                    { key: 'expiry', label: 'Expires', children: item.expiresAt ? new Date(item.expiresAt).toLocaleString() : 'Unknown' },
                  ]} />
                ),
              },
              {
                title: 'Status',
                width: 120,
                render: (_, item) => <Tag color={item.active ? 'green' : 'default'}>{item.active ? 'Active' : 'Expired'}</Tag>,
              },
              {
                title: 'Action',
                width: 140,
                render: (_, item) =>
                  sessionModal.user ? (
                    <Popconfirm
                      title="Revoke this session?"
                      description="The user will be signed out on this device."
                      onConfirm={() => revokeSession(sessionModal.user, item.id)}
                    >
                      <Button size="small" danger>
                        Revoke
                      </Button>
                    </Popconfirm>
                  ) : null,
              },
            ]}
          />
        </Space>
      </Modal>
    </Space>
  );
}
