import React, { useState } from 'react';
import { Card, Form, Input, Select, Button, Space, Typography, Switch, Tabs, Row, Col, message, Divider, Upload, Avatar } from 'antd';
import { SaveOutlined, ReloadOutlined, UserOutlined, LockOutlined, BellOutlined, GlobalOutlined, DatabaseOutlined, ApiOutlined, SettingOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { TextArea } = Input;

const SettingsPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('profile');
  const [loading, setLoading] = useState(false);
  const [profileForm] = Form.useForm();
  const [securityForm] = Form.useForm();
  const [notificationForm] = Form.useForm();
  const [systemForm] = Form.useForm();

  const handleSaveProfile = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('Profile updated successfully');
    }, 1000);
  };

  const handleSaveSecurity = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('Security settings updated successfully');
    }, 1000);
  };

  const handleSaveNotification = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('Notification settings updated successfully');
    }, 1000);
  };

  const handleSaveSystem = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('System settings updated successfully');
    }, 1000);
  };

  const handleResetSettings = () => {
    message.success('Settings reset to default');
  };

  const handleExportSettings = () => {
    message.success('Settings exported successfully');
  };

  const handleImportSettings = () => {
    message.success('Settings imported successfully');
  };

  return (
    <div className="settings-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>System Settings</Title>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={handleResetSettings}>Reset to Default</Button>
          <Button icon={<ReloadOutlined />} onClick={handleExportSettings}>Export Settings</Button>
          <Button icon={<ReloadOutlined />} onClick={handleImportSettings}>Import Settings</Button>
        </Space>
      </div>

      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="Profile" key="profile">
            <div style={{ maxWidth: 800, margin: '0 auto' }}>
              <div style={{ textAlign: 'center', marginBottom: 32 }}>
                <Avatar size={100} icon={<UserOutlined />} style={{ marginBottom: 16 }} />
                <Title level={4}>User Profile</Title>
                <Text type="secondary">Manage your personal information and preferences</Text>
              </div>
              
              <Form
                form={profileForm}
                layout="vertical"
                onFinish={handleSaveProfile}
                initialValues={{
                  username: 'admin',
                  email: 'admin@crawlful.com',
                  firstName: 'Admin',
                  lastName: 'User',
                  phone: '+1-234-567-8900',
                  timezone: 'UTC-8',
                  language: 'en',
                }}
              >
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="username"
                      label="Username"
                      rules={[{ required: true, message: 'Please input your username' }]}
                    >
                      <Input prefix={<UserOutlined />} placeholder="Username" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="email"
                      label="Email"
                      rules={[
                        { required: true, message: 'Please input your email' },
                        { type: 'email', message: 'Please input a valid email' },
                      ]}
                    >
                      <Input placeholder="Email" />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="firstName"
                      label="First Name"
                      rules={[{ required: true, message: 'Please input your first name' }]}
                    >
                      <Input placeholder="First Name" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="lastName"
                      label="Last Name"
                      rules={[{ required: true, message: 'Please input your last name' }]}
                    >
                      <Input placeholder="Last Name" />
                    </Form.Item>
                  </Col>
                </Row>

                <Form.Item
                  name="phone"
                  label="Phone Number"
                >
                  <Input placeholder="Phone Number" />
                </Form.Item>

                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="timezone"
                      label="Timezone"
                      rules={[{ required: true, message: 'Please select your timezone' }]}
                    >
                      <Select placeholder="Select Timezone">
                        <Option value="UTC-8">UTC-8 (Pacific Time)</Option>
                        <Option value="UTC-5">UTC-5 (Eastern Time)</Option>
                        <Option value="UTC+0">UTC+0 (Greenwich Mean Time)</Option>
                        <Option value="UTC+1">UTC+1 (Central European Time)</Option>
                        <Option value="UTC+8">UTC+8 (China Standard Time)</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="language"
                      label="Language"
                      rules={[{ required: true, message: 'Please select your language' }]}
                    >
                      <Select placeholder="Select Language">
                        <Option value="en">English</Option>
                        <Option value="zh">中文</Option>
                        <Option value="es">Español</Option>
                        <Option value="fr">Français</Option>
                        <Option value="de">Deutsch</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>

                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading} block>
                    Save Profile
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </TabPane>

          <TabPane tab="Security" key="security">
            <div style={{ maxWidth: 800, margin: '0 auto' }}>
              <div style={{ textAlign: 'center', marginBottom: 32 }}>
                <Avatar size={100} icon={<LockOutlined />} style={{ marginBottom: 16 }} />
                <Title level={4}>Security Settings</Title>
                <Text type="secondary">Manage your security and authentication preferences</Text>
              </div>

              <Form
                form={securityForm}
                layout="vertical"
                onFinish={handleSaveSecurity}
                initialValues={{
                  currentPassword: '',
                  newPassword: '',
                  confirmPassword: '',
                  twoFactorEnabled: false,
                  loginAlerts: true,
                }}
              >
                <Form.Item
                  name="currentPassword"
                  label="Current Password"
                  rules={[{ required: true, message: 'Please input your current password' }]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="Current Password" />
                </Form.Item>

                <Form.Item
                  name="newPassword"
                  label="New Password"
                  rules={[
                    { required: true, message: 'Please input your new password' },
                    { min: 8, message: 'Password must be at least 8 characters' },
                  ]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="New Password" />
                </Form.Item>

                <Form.Item
                  name="confirmPassword"
                  label="Confirm Password"
                  dependencies={['newPassword']}
                  rules={[
                    { required: true, message: 'Please confirm your password' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('The two passwords do not match'));
                      },
                    }),
                  ]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="Confirm Password" />
                </Form.Item>

                <Divider />

                <Form.Item
                  name="twoFactorEnabled"
                  label="Two-Factor Authentication"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item
                  name="loginAlerts"
                  label="Login Alerts"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading} block>
                    Save Security Settings
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </TabPane>

          <TabPane tab="Notifications" key="notifications">
            <div style={{ maxWidth: 800, margin: '0 auto' }}>
              <div style={{ textAlign: 'center', marginBottom: 32 }}>
                <Avatar size={100} icon={<BellOutlined />} style={{ marginBottom: 16 }} />
                <Title level={4}>Notification Settings</Title>
                <Text type="secondary">Manage your notification preferences</Text>
              </div>

              <Form
                form={notificationForm}
                layout="vertical"
                onFinish={handleSaveNotification}
                initialValues={{
                  emailNotifications: true,
                  pushNotifications: true,
                  orderUpdates: true,
                  priceAlerts: true,
                  inventoryAlerts: true,
                  complianceAlerts: true,
                  marketingEmails: false,
                }}
              >
                <Title level={5}>Email Notifications</Title>
                
                <Form.Item
                  name="emailNotifications"
                  label="Enable Email Notifications"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item
                  name="orderUpdates"
                  label="Order Updates"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item
                  name="priceAlerts"
                  label="Price Alerts"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item
                  name="inventoryAlerts"
                  label="Inventory Alerts"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item
                  name="complianceAlerts"
                  label="Compliance Alerts"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item
                  name="marketingEmails"
                  label="Marketing Emails"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Divider />

                <Title level={5}>Push Notifications</Title>

                <Form.Item
                  name="pushNotifications"
                  label="Enable Push Notifications"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>

                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading} block>
                    Save Notification Settings
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </TabPane>

          <TabPane tab="System" key="system">
            <div style={{ maxWidth: 800, margin: '0 auto' }}>
              <div style={{ textAlign: 'center', marginBottom: 32 }}>
                <Avatar size={100} icon={<SettingOutlined />} style={{ marginBottom: 16 }} />
                <Title level={4}>System Settings</Title>
                <Text type="secondary">Manage system-wide preferences and configurations</Text>
              </div>

              <Form
                form={systemForm}
                layout="vertical"
                onFinish={handleSaveSystem}
                initialValues={{
                  siteName: 'Crawlful Hub',
                  siteUrl: 'https://crawlful.com',
                  defaultCurrency: 'USD',
                  dateFormat: 'YYYY-MM-DD',
                  timeFormat: '24h',
                  apiRateLimit: 1000,
                  dataRetentionDays: 90,
                }}
              >
                <Title level={5}>General Settings</Title>

                <Form.Item
                  name="siteName"
                  label="Site Name"
                  rules={[{ required: true, message: 'Please input site name' }]}
                >
                  <Input placeholder="Site Name" />
                </Form.Item>

                <Form.Item
                  name="siteUrl"
                  label="Site URL"
                  rules={[{ required: true, message: 'Please input site URL' }]}
                >
                  <Input placeholder="Site URL" />
                </Form.Item>

                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      name="defaultCurrency"
                      label="Default Currency"
                      rules={[{ required: true, message: 'Please select default currency' }]}
                    >
                      <Select placeholder="Select Currency">
                        <Option value="USD">USD - US Dollar</Option>
                        <Option value="EUR">EUR - Euro</Option>
                        <Option value="GBP">GBP - British Pound</Option>
                        <Option value="CNY">CNY - Chinese Yuan</Option>
                        <Option value="JPY">JPY - Japanese Yen</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      name="dateFormat"
                      label="Date Format"
                      rules={[{ required: true, message: 'Please select date format' }]}
                    >
                      <Select placeholder="Select Date Format">
                        <Option value="YYYY-MM-DD">YYYY-MM-DD</Option>
                        <Option value="MM/DD/YYYY">MM/DD/YYYY</Option>
                        <Option value="DD/MM/YYYY">DD/MM/YYYY</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>

                <Form.Item
                  name="timeFormat"
                  label="Time Format"
                  rules={[{ required: true, message: 'Please select time format' }]}
                >
                  <Select placeholder="Select Time Format">
                    <Option value="24h">24-hour</Option>
                    <Option value="12h">12-hour</Option>
                  </Select>
                </Form.Item>

                <Divider />

                <Title level={5}>API Settings</Title>

                <Form.Item
                  name="apiRateLimit"
                  label="API Rate Limit (requests per minute)"
                  rules={[{ required: true, message: 'Please input API rate limit' }]}
                >
                  <Input type="number" placeholder="API Rate Limit" />
                </Form.Item>

                <Divider />

                <Title level={5}>Data Settings</Title>

                <Form.Item
                  name="dataRetentionDays"
                  label="Data Retention Period (days)"
                  rules={[{ required: true, message: 'Please input data retention period' }]}
                >
                  <Input type="number" placeholder="Data Retention Period" />
                </Form.Item>

                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading} block>
                    Save System Settings
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </TabPane>

          <TabPane tab="Integrations" key="integrations">
            <div style={{ maxWidth: 800, margin: '0 auto' }}>
              <div style={{ textAlign: 'center', marginBottom: 32 }}>
                <Avatar size={100} icon={<ApiOutlined />} style={{ marginBottom: 16 }} />
                <Title level={4}>Integrations</Title>
                <Text type="secondary">Manage third-party service integrations</Text>
              </div>

              <Card title="Platform Integrations" style={{ marginBottom: 24 }}>
                <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
                    <div>
                      <Text strong>Amazon Integration</Text>
                      <br />
                      <Text type="secondary">Connect your Amazon seller account</Text>
                    </div>
                    <Button type="primary">Connect</Button>
                  </div>
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
                    <div>
                      <Text strong>eBay Integration</Text>
                      <br />
                      <Text type="secondary">Connect your eBay seller account</Text>
                    </div>
                    <Button type="primary">Connect</Button>
                  </div>
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
                    <div>
                      <Text strong>Shopee Integration</Text>
                      <br />
                      <Text type="secondary">Connect your Shopee seller account</Text>
                    </div>
                    <Button type="primary">Connect</Button>
                  </div>
                </Space>
              </Card>

              <Card title="Service Integrations" style={{ marginBottom: 24 }}>
                <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
                    <div>
                      <Text strong>Payment Gateway</Text>
                      <br />
                      <Text type="secondary">Connect payment processing service</Text>
                    </div>
                    <Button type="primary">Connect</Button>
                  </div>
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
                    <div>
                      <Text strong>Shipping Service</Text>
                      <br />
                      <Text type="secondary">Connect logistics and shipping service</Text>
                    </div>
                    <Button type="primary">Connect</Button>
                  </div>
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0' }}>
                    <div>
                      <Text strong>Analytics Service</Text>
                      <br />
                      <Text type="secondary">Connect analytics and reporting service</Text>
                    </div>
                    <Button type="primary">Connect</Button>
                  </div>
                </Space>
              </Card>

              <Card title="API Configuration">
                <Form layout="vertical">
                  <Form.Item label="API Key">
                    <Input.Password placeholder="Enter your API key" />
                  </Form.Item>
                  
                  <Form.Item label="API Secret">
                    <Input.Password placeholder="Enter your API secret" />
                  </Form.Item>
                  
                  <Form.Item label="Webhook URL">
                    <Input placeholder="Enter webhook URL" />
                  </Form.Item>
                  
                  <Button type="primary" icon={<SaveOutlined />} block>
                    Save API Configuration
                  </Button>
                </Form>
              </Card>
            </div>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default SettingsPage;