import { useState } from 'react';
import {
  Modal,
  Table,
  Button,
  Space,
  Tag,
  Form,
  Input,
  Select,
  Popconfirm,
  Typography,
  Alert,
  Tooltip,
} from 'antd';
import { showSuccess, showError } from '@/lib/errorHandling';
import { decodeHtmlEntities } from '@/lib/formatters';
import {
  UserAddOutlined,
  DeleteOutlined,
  EditOutlined,
  TeamOutlined,
  CrownOutlined,
  UserOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { useActiveCompany, useCanAdmin, getRoleLabel, getRoleColor } from '@/stores/companyStore';
import { useCompanyUsers } from '@/api/queries/companyQueries';
import { useGrantUserAccess, useChangeUserRole, useRevokeUserAccess } from '@/api/mutations/companyMutations';
import type { UserCompanyAccess, CompanyRole } from '@/types/accounting';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

const { Text } = Typography;

interface UserAccessManagerProps {
  open: boolean;
  onClose: () => void;
}

interface InviteFormValues {
  userId: string;
  role: CompanyRole;
}

const roleOptions = [
  { value: 'owner', label: 'Ejer', icon: <CrownOutlined />, description: 'Fuld adgang inkl. brugeradministration' },
  { value: 'accountant', label: 'Bogholder', icon: <UserOutlined />, description: 'Kan bogføre og redigere' },
  { value: 'viewer', label: 'Læser', icon: <EyeOutlined />, description: 'Kun læseadgang' },
];

export default function UserAccessManager({ open, onClose }: UserAccessManagerProps) {
  const activeCompany = useActiveCompany();
  const canAdmin = useCanAdmin();
  const [inviteModalOpen, setInviteModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<UserCompanyAccess | null>(null);
  const [form] = Form.useForm<InviteFormValues>();

  const { data: users = [], isLoading, refetch } = useCompanyUsers(activeCompany?.id);
  const grantAccess = useGrantUserAccess();
  const changeRole = useChangeUserRole();
  const revokeAccess = useRevokeUserAccess();

  const handleInvite = async (values: InviteFormValues) => {
    if (!activeCompany) return;

    try {
      await grantAccess.mutateAsync({
        userId: values.userId,
        companyId: activeCompany.id,
        role: values.role,
      });
      showSuccess(`Bruger ${decodeHtmlEntities(values.userId)} er blevet tilføjet som ${getRoleLabel(values.role)}`);
      setInviteModalOpen(false);
      form.resetFields();
      refetch();
    } catch (error) {
      showError('Kunne ikke tilføje bruger. Prøv igen.');
    }
  };

  const handleChangeRole = async (userId: string, newRole: CompanyRole) => {
    if (!activeCompany) return;

    try {
      await changeRole.mutateAsync({
        userId,
        companyId: activeCompany.id,
        newRole,
      });
      showSuccess(`Brugerens rolle er ændret til ${getRoleLabel(newRole)}`);
      setEditingUser(null);
      refetch();
    } catch (error) {
      showError('Kunne ikke ændre rolle. Prøv igen.');
    }
  };

  const handleRevoke = async (userId: string) => {
    if (!activeCompany) return;

    try {
      await revokeAccess.mutateAsync({
        userId,
        companyId: activeCompany.id,
      });
      showSuccess('Brugerens adgang er blevet fjernet');
      refetch();
    } catch (error) {
      showError('Kunne ikke fjerne adgang. Prøv igen.');
    }
  };

  const columns: ColumnsType<UserCompanyAccess> = [
    {
      title: 'Bruger',
      dataIndex: 'userId',
      key: 'userId',
      render: (userId: string) => (
        <Space>
          <UserOutlined />
          <Text>{decodeHtmlEntities(userId)}</Text>
        </Space>
      ),
    },
    {
      title: 'Rolle',
      dataIndex: 'role',
      key: 'role',
      render: (role: CompanyRole, record) => {
        if (editingUser?.userId === record.userId) {
          return (
            <Select
              defaultValue={role}
              style={{ width: 140 }}
              onChange={(newRole) => handleChangeRole(record.userId, newRole)}
              onBlur={() => setEditingUser(null)}
              autoFocus
              options={roleOptions.map((opt) => ({
                value: opt.value,
                label: (
                  <Space>
                    {opt.icon}
                    {opt.label}
                  </Space>
                ),
              }))}
            />
          );
        }
        return (
          <Tag color={getRoleColor(role)} icon={
            role === 'owner' ? <CrownOutlined /> :
            role === 'accountant' ? <UserOutlined /> :
            <EyeOutlined />
          }>
            {getRoleLabel(role)}
          </Tag>
        );
      },
    },
    {
      title: 'Tilføjet',
      dataIndex: 'grantedAt',
      key: 'grantedAt',
      render: (date: string) => dayjs(date).format('D. MMM YYYY'),
    },
    {
      title: 'Tilføjet af',
      dataIndex: 'grantedBy',
      key: 'grantedBy',
      render: (grantedBy: string) => (
        <Text type="secondary">{decodeHtmlEntities(grantedBy)}</Text>
      ),
    },
    {
      title: 'Handlinger',
      key: 'actions',
      width: 120,
      render: (_, record) => (
        <Space>
          <Tooltip title="Ændr rolle">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => setEditingUser(record)}
              disabled={!canAdmin}
            />
          </Tooltip>
          <Popconfirm
            title="Fjern adgang"
            description={`Er du sikker på at du vil fjerne ${decodeHtmlEntities(record.userId)}'s adgang?`}
            onConfirm={() => handleRevoke(record.userId)}
            okText="Ja, fjern"
            cancelText="Annuller"
            okButtonProps={{ danger: true }}
          >
            <Tooltip title="Fjern adgang">
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
                disabled={!canAdmin}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <>
      <Modal
        title={
          <Space>
            <TeamOutlined />
            <span>Brugeradgang - {activeCompany?.name}</span>
          </Space>
        }
        open={open}
        onCancel={onClose}
        width={800}
        footer={[
          <Button key="close" onClick={onClose}>
            Luk
          </Button>,
          canAdmin && (
            <Button
              key="invite"
              type="primary"
              icon={<UserAddOutlined />}
              onClick={() => setInviteModalOpen(true)}
            >
              Tilføj bruger
            </Button>
          ),
        ]}
      >
        {!canAdmin && (
          <Alert
            message="Kun ejere kan administrere brugeradgang"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        <Table
          dataSource={users}
          columns={columns}
          rowKey="id"
          loading={isLoading}
          pagination={false}
          size="middle"
          locale={{
            emptyText: 'Ingen brugere har adgang til denne virksomhed endnu',
          }}
        />
      </Modal>

      {/* Invite User Modal */}
      <Modal
        title={
          <Space>
            <UserAddOutlined />
            <span>Tilføj bruger</span>
          </Space>
        }
        open={inviteModalOpen}
        onCancel={() => {
          setInviteModalOpen(false);
          form.resetFields();
        }}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleInvite}
          initialValues={{ role: 'viewer' }}
        >
          <Form.Item
            name="userId"
            label="Bruger-ID eller email"
            rules={[{ required: true, message: 'Indtast bruger-ID eller email' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="fx. bruger@example.com"
            />
          </Form.Item>

          <Form.Item
            name="role"
            label="Rolle"
            rules={[{ required: true, message: 'Vælg en rolle' }]}
          >
            <Select
              options={roleOptions.map((opt) => ({
                value: opt.value,
                label: (
                  <Space direction="vertical" size={0}>
                    <Space>
                      {opt.icon}
                      <Text strong>{opt.label}</Text>
                    </Space>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {opt.description}
                    </Text>
                  </Space>
                ),
              }))}
              optionRender={(option) => (
                <div style={{ padding: '4px 0' }}>
                  {option.label}
                </div>
              )}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setInviteModalOpen(false);
                form.resetFields();
              }}>
                Annuller
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={grantAccess.isPending}
              >
                Tilføj bruger
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
