import React, { useState } from 'react';
import {
  Card,
  Typography,
  Space,
  Form,
  Input,
  Button,
  Select,
  Alert,
  Row,
  Col,
  Tag,
  Modal,
  message,
} from 'antd';
import {
  UserOutlined,
  LoginOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { apiService } from '../services/apiService';
import { useAuth } from '../contexts/AuthContext';

const { Title, Text } = Typography;
const { Option } = Select;

const Users: React.FC = () => {
  const { user } = useAuth();
  const [loginForm] = Form.useForm();
  const [renewForm] = Form.useForm();
  const [loginModalVisible, setLoginModalVisible] = useState(false);
  const [renewModalVisible, setRenewModalVisible] = useState(false);
  const [loginResult, setLoginResult] = useState<any>(null);
  const [renewResult, setRenewResult] = useState<any>(null);

  const handleUserLogin = async (values: any) => {
    try {
      const response = await apiService.login(
        values.app_id,
        values.permissions || [],
        values.redirect_uri
      );
      setLoginResult(response);
      message.success('User login initiated successfully');
    } catch (error) {
      console.error('Failed to initiate user login:', error);
      message.error('Failed to initiate user login');
    }
  };

  const handleTokenRenewal = async (values: any) => {
    try {
      const response = await apiService.renewToken(
        values.app_id,
        values.user_id,
        values.token
      );
      setRenewResult(response);
      message.success('Token renewed successfully');
    } catch (error) {
      console.error('Failed to renew token:', error);
      message.error('Failed to renew token');
    }
  };

  const availablePermissions = [
    'app.read',
    'app.write',
    'app.delete',
    'token.read',
    'token.create',
    'token.revoke',
    'repo.read',
    'repo.write',
    'repo.admin',
    'permission.read',
    'permission.write',
    'permission.grant',
    'permission.revoke',
  ];

  return (
    <div>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <div>
          <Title level={2}>User Management</Title>
          <Text type="secondary">
            Manage user authentication and token operations
          </Text>
        </div>

        {/* Current User Info */}
        <Card title="Current User">
          <Row gutter={16}>
            <Col span={8}>
              <Text strong>Email:</Text>
              <div>{user?.email}</div>
            </Col>
            <Col span={8}>
              <Text strong>Status:</Text>
              <div>
                <Tag color="green" icon={<CheckCircleOutlined />}>
                  AUTHENTICATED
                </Tag>
              </div>
            </Col>
            <Col span={8}>
              <Text strong>Permissions:</Text>
              <div style={{ marginTop: '8px' }}>
                {user?.permissions.map(permission => (
                  <Tag key={permission} color="blue" style={{ marginBottom: '4px' }}>
                    {permission}
                  </Tag>
                ))}
              </div>
            </Col>
          </Row>
        </Card>

        {/* User Operations */}
        <Row gutter={16}>
          <Col span={12}>
            <Card
              title="User Login"
              extra={
                <Button
                  type="primary"
                  icon={<LoginOutlined />}
                  onClick={() => setLoginModalVisible(true)}
                >
                  Initiate Login
                </Button>
              }
            >
              <Text type="secondary">
                Initiate a user authentication flow for an application. This will generate
                a user token that can be used for API access with specific permissions.
              </Text>
            </Card>
          </Col>
          <Col span={12}>
            <Card
              title="Token Renewal"
              extra={
                <Button
                  icon={<ClockCircleOutlined />}
                  onClick={() => setRenewModalVisible(true)}
                >
                  Renew Token
                </Button>
              }
            >
              <Text type="secondary">
                Renew an existing user token to extend its validity period.
                This is useful for maintaining long-running sessions.
              </Text>
            </Card>
          </Col>
        </Row>

        {/* Information Cards */}
        <Row gutter={16}>
          <Col span={8}>
            <Card>
              <div style={{ textAlign: 'center' }}>
                <UserOutlined style={{ fontSize: '32px', color: '#1890ff', marginBottom: '8px' }} />
                <div style={{ fontSize: '24px', fontWeight: 'bold' }}>1</div>
                <div>Active Users</div>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <div style={{ textAlign: 'center' }}>
                <LoginOutlined style={{ fontSize: '32px', color: '#52c41a', marginBottom: '8px' }} />
                <div style={{ fontSize: '24px', fontWeight: 'bold' }}>Demo</div>
                <div>Authentication Mode</div>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <div style={{ textAlign: 'center' }}>
                <CheckCircleOutlined style={{ fontSize: '32px', color: '#722ed1', marginBottom: '8px' }} />
                <div style={{ fontSize: '24px', fontWeight: 'bold' }}>Active</div>
                <div>Session Status</div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* Authentication Flow Information */}
        <Card title="Authentication Flow Information">
          <Space direction="vertical" size="middle" style={{ width: '100%' }}>
            <Alert
              message="Demo Mode"
              description="This frontend is running in demo mode. In a production environment, user authentication would integrate with your identity provider (OAuth2, SAML, etc.)."
              type="info"
              showIcon
            />
            
            <div>
              <Title level={4}>Supported Authentication Methods</Title>
              <ul>
                <li><strong>Header Authentication:</strong> Uses X-User-Email header for demo purposes</li>
                <li><strong>OAuth2:</strong> Standard OAuth2 flow with authorization code grant</li>
                <li><strong>SAML:</strong> SAML 2.0 single sign-on integration</li>
                <li><strong>JWT:</strong> JSON Web Token based authentication</li>
              </ul>
            </div>

            <div>
              <Title level={4}>Token Types</Title>
              <ul>
                <li><strong>User Tokens:</strong> Short-lived tokens for authenticated users</li>
                <li><strong>Static Tokens:</strong> Long-lived tokens for service-to-service communication</li>
                <li><strong>Renewal Tokens:</strong> Used to extend user token validity</li>
              </ul>
            </div>
          </Space>
        </Card>
      </Space>

      {/* User Login Modal */}
      <Modal
        title="Initiate User Login"
        open={loginModalVisible}
        onCancel={() => {
          setLoginModalVisible(false);
          setLoginResult(null);
        }}
        onOk={() => loginForm.submit()}
        width={600}
      >
        {loginResult ? (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <Alert
              message="Login Flow Initiated"
              description="The user login flow has been initiated successfully."
              type="success"
              showIcon
            />
            
            <Card title="Login Response">
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                {loginResult.redirect_url && (
                  <div>
                    <Text strong>Redirect URL:</Text>
                    <div>
                      <a href={loginResult.redirect_url} target="_blank" rel="noopener noreferrer">
                        {loginResult.redirect_url}
                      </a>
                    </div>
                  </div>
                )}
                
                {loginResult.token && (
                  <div>
                    <Text strong>Token:</Text>
                    <div>
                      <Input.TextArea
                        value={loginResult.token}
                        readOnly
                        rows={3}
                        style={{ fontFamily: 'monospace' }}
                      />
                    </div>
                  </div>
                )}
                
                {loginResult.user_id && (
                  <div>
                    <Text strong>User ID:</Text>
                    <div>{loginResult.user_id}</div>
                  </div>
                )}
                
                {loginResult.expires_in && (
                  <div>
                    <Text strong>Expires In:</Text>
                    <div>{loginResult.expires_in} seconds</div>
                  </div>
                )}
              </Space>
            </Card>
          </Space>
        ) : (
          <Form
            form={loginForm}
            layout="vertical"
            onFinish={handleUserLogin}
          >
            <Form.Item
              name="app_id"
              label="Application ID"
              rules={[{ required: true, message: 'Please enter application ID' }]}
            >
              <Input placeholder="com.example.app" />
            </Form.Item>

            <Form.Item
              name="permissions"
              label="Requested Permissions"
            >
              <Select
                mode="multiple"
                placeholder="Select permissions"
                allowClear
              >
                {availablePermissions.map(permission => (
                  <Option key={permission} value={permission}>
                    {permission}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="redirect_uri"
              label="Redirect URI (Optional)"
            >
              <Input placeholder="https://example.com/callback" />
            </Form.Item>
          </Form>
        )}
      </Modal>

      {/* Token Renewal Modal */}
      <Modal
        title="Renew User Token"
        open={renewModalVisible}
        onCancel={() => {
          setRenewModalVisible(false);
          setRenewResult(null);
        }}
        onOk={() => renewForm.submit()}
        width={600}
      >
        {renewResult ? (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <Alert
              message="Token Renewed Successfully"
              description="The user token has been renewed with extended validity."
              type="success"
              showIcon
            />
            
            <Card title="Renewal Response">
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <div>
                  <Text strong>New Token:</Text>
                  <div>
                    <Input.TextArea
                      value={renewResult.token}
                      readOnly
                      rows={3}
                      style={{ fontFamily: 'monospace' }}
                    />
                  </div>
                </div>
                
                <div>
                  <Text strong>Expires At:</Text>
                  <div>{new Date(renewResult.expires_at).toLocaleString()}</div>
                </div>
                
                <div>
                  <Text strong>Max Valid At:</Text>
                  <div>{new Date(renewResult.max_valid_at).toLocaleString()}</div>
                </div>
              </Space>
            </Card>
          </Space>
        ) : (
          <Form
            form={renewForm}
            layout="vertical"
            onFinish={handleTokenRenewal}
          >
            <Form.Item
              name="app_id"
              label="Application ID"
              rules={[{ required: true, message: 'Please enter application ID' }]}
            >
              <Input placeholder="com.example.app" />
            </Form.Item>

            <Form.Item
              name="user_id"
              label="User ID"
              rules={[{ required: true, message: 'Please enter user ID' }]}
            >
              <Input placeholder="user@example.com" />
            </Form.Item>

            <Form.Item
              name="token"
              label="Current Token"
              rules={[{ required: true, message: 'Please enter current token' }]}
            >
              <Input.TextArea
                placeholder="Enter the current user token"
                rows={3}
                style={{ fontFamily: 'monospace' }}
              />
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default Users;
