import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Descriptions,
  Divider,
  message,
  Tag,
  Row,
  Col,
  Statistic,
  Progress,
  Alert,
  Tabs,
  Tooltip,
} from 'antd';
import {
  SafetyCertificateOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
  LoadingOutlined,
  SyncOutlined,
  FileSearchOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { certificateDataSource, Certificate } from '@/services/certificateDataSource';

const { Option } = Select;
const { TabPane } = Tabs;

interface ComplianceResult {
  id: string;
  productId: string;
  productName: string;
  platform: string;
  checkDate: string;
  overallStatus: 'PASS' | 'FAIL' | 'WARNING' | 'PENDING';
  checks: {
    certCompliance: boolean;
    labelCompliance: boolean;
    descriptionCompliance: boolean;
    imageCompliance: boolean;
    priceCompliance: boolean;
    policyCompliance: boolean;
  };
  issues: string[];
  score: number;
}

const PLATFORMS = [
  { value: 'Amazon', label: 'Amazon', rules: 15 },
  { value: 'eBay', label: 'eBay', rules: 12 },
  { value: 'Shopify', label: 'Shopify', rules: 10 },
  { value: 'Walmart', label: 'Walmart', rules: 14 },
  { value: 'AliExpress', label: 'AliExpress', rules: 11 },
];

const MOCK_PRODUCTS = [
  { id: 'P001', name: 'Industrial Sensor A', hasCert: true },
  { id: 'P002', name: 'Control Module B', hasCert: true },
  { id: 'P003', name: 'Power Supply Unit C', hasCert: false },
  { id: 'P004', name: 'Communication Gateway D', hasCert: true },
];

const MOCK_RESULTS: ComplianceResult[] = [
  {
    id: '1',
    productId: 'P001',
    productName: 'Industrial Sensor A',
    platform: 'Amazon',
    checkDate: '2026-03-18 10:30:00',
    overallStatus: 'PASS',
    checks: {
      certCompliance: true,
      labelCompliance: true,
      descriptionCompliance: true,
      imageCompliance: true,
      priceCompliance: true,
      policyCompliance: true,
    },
    issues: [],
    score: 100,
  },
  {
    id: '2',
    productId: 'P002',
    productName: 'Control Module B',
    platform: 'Amazon',
    checkDate: '2026-03-18 09:15:00',
    overallStatus: 'WARNING',
    checks: {
      certCompliance: true,
      labelCompliance: true,
      descriptionCompliance: false,
      imageCompliance: true,
      priceCompliance: true,
      policyCompliance: false,
    },
    issues: [
      'Product description missing warranty information',
      'Contains restricted keyword in bullet points',
    ],
    score: 75,
  },
  {
    id: '3',
    productId: 'P003',
    productName: 'Power Supply Unit C',
    platform: 'eBay',
    checkDate: '2026-03-17 16:00:00',
    overallStatus: 'FAIL',
    checks: {
      certCompliance: false,
      labelCompliance: true,
      descriptionCompliance: false,
      imageCompliance: false,
      priceCompliance: true,
      policyCompliance: true,
    },
    issues: [
      'Missing required CE certification',
      'Product images missing watermark',
      'Description contains promotional content',
    ],
    score: 40,
  },
];

export const ComplianceCheck: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<ComplianceResult[]>(MOCK_RESULTS);
  const [checkModalVisible, setCheckModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedResult, setSelectedResult] = useState<ComplianceResult | null>(null);
  const [activeTab, setActiveTab] = useState('all');

  const handleRunCheck = async (values: any) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const product = MOCK_PRODUCTS.find(p => p.id === values.productId);
      const hasCert = product?.hasCert || false;
      
      const newResult: ComplianceResult = {
        id: `${Date.now()}`,
        productId: values.productId,
        productName: product?.name || '',
        platform: values.platform,
        checkDate: new Date().toISOString(),
        overallStatus: hasCert ? 'PASS' : 'FAIL',
        checks: {
          certCompliance: hasCert,
          labelCompliance: true,
          descriptionCompliance: hasCert,
          imageCompliance: true,
          priceCompliance: true,
          policyCompliance: hasCert,
        },
        issues: hasCert ? [] : ['Missing required certification'],
        score: hasCert ? 100 : 30,
      };

      setResults([newResult, ...results]);
      message.success('Compliance check completed');
      setCheckModalVisible(false);
      form.resetFields();
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (result: ComplianceResult) => {
    setSelectedResult(result);
    setDetailModalVisible(true);
  };

  const getStatusConfig = (status: string) => {
    const configs: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
      PASS: { color: 'success', text: 'Pass', icon: <CheckCircleOutlined /> },
      FAIL: { color: 'error', text: 'Fail', icon: <CloseCircleOutlined /> },
      WARNING: { color: 'warning', text: 'Warning', icon: <WarningOutlined /> },
      PENDING: { color: 'processing', text: 'Pending', icon: <LoadingOutlined /> },
    };
    return configs[status];
  };

  const getFilteredResults = () => {
    if (activeTab === 'all') return results;
    return results.filter(r => r.overallStatus.toLowerCase() === activeTab);
  };

  const columns: ColumnsType<ComplianceResult> = [
    {
      title: 'Product ID',
      dataIndex: 'productId',
      key: 'productId',
      width: 100,
    },
    {
      title: 'Product Name',
      dataIndex: 'productName',
      key: 'productName',
      width: 180,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
      render: (platform: string) => <Tag>{platform}</Tag>,
    },
    {
      title: 'Score',
      dataIndex: 'score',
      key: 'score',
      width: 150,
      render: (score: number, record: ComplianceResult) => (
        <Tooltip title={`${record.overallStatus}`}>
          <Progress 
            percent={score} 
            size="small"
            status={record.overallStatus === 'PASS' ? 'success' : record.overallStatus === 'FAIL' ? 'exception' : 'normal'}
            strokeColor={record.overallStatus === 'PASS' ? '#52c41a' : record.overallStatus === 'FAIL' ? '#ff4d4f' : '#faad14'}
          />
        </Tooltip>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'overallStatus',
      key: 'overallStatus',
      width: 100,
      render: (status: string) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: 'Check Date',
      dataIndex: 'checkDate',
      key: 'checkDate',
      width: 160,
    },
    {
      title: 'Issues',
      dataIndex: 'issues',
      key: 'issues',
      width: 100,
      render: (issues: string[]) => issues.length > 0 ? (
        <Tag color="error">{issues.length} issues</Tag>
      ) : (
        <Tag color="success">No issues</Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_, record) => (
        <Button type="link" icon={<FileSearchOutlined />} onClick={() => handleViewDetail(record)}>
          Details
        </Button>
      ),
    },
  ];

  const stats = {
    total: results.length,
    pass: results.filter(r => r.overallStatus === 'PASS').length,
    warning: results.filter(r => r.overallStatus === 'WARNING').length,
    fail: results.filter(r => r.overallStatus === 'FAIL').length,
  };

  return (
    <div className="compliance-check-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Checks" value={stats.total} prefix={<SafetyCertificateOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Passed" 
              value={stats.pass} 
              valueStyle={{ color: '#52c41a' }} 
              prefix={<CheckCircleOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Warnings" 
              value={stats.warning} 
              valueStyle={{ color: '#faad14' }} 
              prefix={<WarningOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Failed" 
              value={stats.fail} 
              valueStyle={{ color: '#ff4d4f' }} 
              prefix={<CloseCircleOutlined />} 
            />
          </Card>
        </Col>
      </Row>

      <Card title="Compliance Check Results" extra={
        <Button type="primary" icon={<SyncOutlined />} onClick={() => setCheckModalVisible(true)}>
          Run New Check
        </Button>
      }>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="All" key="all" />
          <TabPane tab="Pass" key="pass" />
          <TabPane tab="Warning" key="warning" />
          <TabPane tab="Fail" key="fail" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={getFilteredResults()}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="Run Compliance Check"
        open={checkModalVisible}
        onCancel={() => setCheckModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form form={form} layout="vertical" onFinish={handleRunCheck}>
          <Form.Item name="productId" label="Product" rules={[{ required: true }]}>
            <Select placeholder="Select Product">
              {MOCK_PRODUCTS.map(p => (
                <Option key={p.id} value={p.id}>
                  {p.id} - {p.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="platform" label="Platform" rules={[{ required: true }]}>
            <Select placeholder="Select Platform">
              {PLATFORMS.map(p => (
                <Option key={p.value} value={p.value}>
                  {p.label} ({p.rules} rules)
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Alert
            message="Compliance Check Scope"
            description="The check will validate your product against platform-specific rules including certification requirements, labeling standards, description guidelines, image requirements, pricing policies, and platform policies."
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setCheckModalVisible(false)} style={{ marginRight: 8 }}>Cancel</Button>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SafetyCertificateOutlined />}>
              Start Check
            </Button>
          </div>
        </Form>
      </Modal>

      <Modal
        title="Compliance Check Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>Close</Button>,
        ]}
        width={700}
      >
        {selectedResult && (
          <>
            <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="Product">{selectedResult.productName}</Descriptions.Item>
              <Descriptions.Item label="Product ID">{selectedResult.productId}</Descriptions.Item>
              <Descriptions.Item label="Platform">
                <Tag>{selectedResult.platform}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Check Date">{selectedResult.checkDate}</Descriptions.Item>
              <Descriptions.Item label="Overall Status">
                <Tag color={getStatusConfig(selectedResult.overallStatus).color}>
                  {getStatusConfig(selectedResult.overallStatus).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Compliance Score">
                <Progress 
                  percent={selectedResult.score} 
                  status={selectedResult.overallStatus === 'PASS' ? 'success' : 'exception'}
                  style={{ width: 150 }}
                />
              </Descriptions.Item>
            </Descriptions>

            <Divider>Compliance Checks</Divider>

            <Row gutter={[16, 16]}>
              <Col span={8}>
                <Card size="small">
                  <Statistic 
                    title="Certification Compliance" 
                    value={selectedResult.checks.certCompliance ? 'PASS' : 'FAIL'} 
                    valueStyle={{ color: selectedResult.checks.certCompliance ? '#52c41a' : '#ff4d4f' }}
                    prefix={selectedResult.checks.certCompliance ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic 
                    title="Label Compliance" 
                    value={selectedResult.checks.labelCompliance ? 'PASS' : 'FAIL'} 
                    valueStyle={{ color: selectedResult.checks.labelCompliance ? '#52c41a' : '#ff4d4f' }}
                    prefix={selectedResult.checks.labelCompliance ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic 
                    title="Description Compliance" 
                    value={selectedResult.checks.descriptionCompliance ? 'PASS' : 'FAIL'} 
                    valueStyle={{ color: selectedResult.checks.descriptionCompliance ? '#52c41a' : '#ff4d4f' }}
                    prefix={selectedResult.checks.descriptionCompliance ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic 
                    title="Image Compliance" 
                    value={selectedResult.checks.imageCompliance ? 'PASS' : 'FAIL'} 
                    valueStyle={{ color: selectedResult.checks.imageCompliance ? '#52c41a' : '#ff4d4f' }}
                    prefix={selectedResult.checks.imageCompliance ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic 
                    title="Price Compliance" 
                    value={selectedResult.checks.priceCompliance ? 'PASS' : 'FAIL'} 
                    valueStyle={{ color: selectedResult.checks.priceCompliance ? '#52c41a' : '#ff4d4f' }}
                    prefix={selectedResult.checks.priceCompliance ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic 
                    title="Policy Compliance" 
                    value={selectedResult.checks.policyCompliance ? 'PASS' : 'FAIL'} 
                    valueStyle={{ color: selectedResult.checks.policyCompliance ? '#52c41a' : '#ff4d4f' }}
                    prefix={selectedResult.checks.policyCompliance ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  />
                </Card>
              </Col>
            </Row>

            {selectedResult.issues.length > 0 && (
              <>
                <Divider>Issues Found</Divider>
                <Alert
                  type="error"
                  message={`${selectedResult.issues.length} Issues Detected`}
                  description={
                    <ul style={{ marginBottom: 0, paddingLeft: 20 }}>
                      {selectedResult.issues.map((issue, index) => (
                        <li key={index}>{issue}</li>
                      ))}
                    </ul>
                  }
                />
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default ComplianceCheck;
