import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  InputNumber,
  Descriptions,
  Divider,
  message,
  Tag,
  Tabs,
  Row,
  Col,
  Statistic,
  Alert,
  Tooltip,
  Badge,
  Upload,
} from 'antd';
import {
  UserOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  StopOutlined,
  ExclamationCircleOutlined,
  UploadOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { blacklistDataSource, BlacklistRecord } from '@/services/blacklistDataSource';

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

interface BlacklistFormData {
  shop_id: string;
  buyer_id: string;
  buyer_name: string;
  buyer_email: string;
  buyer_phone?: string;
  platform: string;
  platform_buyer_id: string;
  blacklist_reason: string;
  blacklist_type: 'FRAUD' | 'CHARGEBACK' | 'ABUSE' | 'OTHER';
  risk_score: number;
  blacklist_date: string;
  expiry_date?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'EXPIRED';
  evidence?: string;
  created_by: string;
  trace_id: string;
  created_at: string;
  updated_at: string;
}

const BLACKLIST_TYPES = [
  { value: 'FRAUD', label: 'Fraud', color: 'red' },
  { value: 'CHARGEBACK', label: 'Chargeback', color: 'orange' },
  { value: 'ABUSE', label: 'Abuse', color: 'purple' },
  { value: 'OTHER', label: 'Other', color: 'default' },
];

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  ACTIVE: { color: 'error', text: 'Active', icon: <StopOutlined /> },
  INACTIVE: { color: 'default', text: 'Inactive', icon: <CloseCircleOutlined /> },
  EXPIRED: { color: 'default', text: 'Expired', icon: <ExclamationCircleOutlined /> },
};

const PLATFORMS = [
  'Amazon',
  'eBay',
  'Shopify',
  'Walmart',
  'TikTok Shop',
  'Temu',
  'Alibaba',
  'Other',
];

const MOCK_BLACKLISTS: BlacklistRecord[] = [
  {
    id: '1',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-001',
    buyer_name: 'John Smith',
    buyer_email: 'john.smith@example.com',
    buyer_phone: '+1-555-0101',
    platform: 'Amazon',
    platform_buyer_id: 'AMZ-001',
    blacklist_reason: 'Multiple fraudulent transactions',
    blacklist_type: 'FRAUD',
    risk_score: 85,
    blacklist_date: '2026-01-15',
    expiry_date: '2027-01-15',
    status: 'ACTIVE',
    evidence: 'Transaction records, IP logs',
    created_by: 'admin',
    trace_id: 'trace-001',
    created_at: '2026-01-15 10:00:00',
    updated_at: '2026-01-15 10:00:00',
  },
  {
    id: '2',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-002',
    buyer_name: 'Jane Doe',
    buyer_email: 'jane.doe@example.com',
    platform: 'eBay',
    platform_buyer_id: 'EBAY-002',
    blacklist_reason: 'Excessive chargebacks',
    blacklist_type: 'CHARGEBACK',
    risk_score: 75,
    blacklist_date: '2026-02-20',
    expiry_date: '2026-08-20',
    status: 'ACTIVE',
    evidence: 'Chargeback documentation',
    created_by: 'admin',
    trace_id: 'trace-002',
    created_at: '2026-02-20 14:30:00',
    updated_at: '2026-02-20 14:30:00',
  },
  {
    id: '3',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-003',
    buyer_name: 'Mike Johnson',
    buyer_email: 'mike.j@example.com',
    platform: 'Amazon',
    platform_buyer_id: 'AMZ-003',
    blacklist_reason: 'Abusive behavior towards support',
    blacklist_type: 'ABUSE',
    risk_score: 60,
    blacklist_date: '2026-03-01',
    expiry_date: '2026-06-01',
    status: 'ACTIVE',
    evidence: 'Support chat logs',
    created_by: 'admin',
    trace_id: 'trace-003',
    created_at: '2026-03-01 09:15:00',
    updated_at: '2026-03-01 09:15:00',
  },
  {
    id: '4',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    buyer_id: 'buyer-004',
    buyer_name: 'Sarah Wilson',
    buyer_email: 'sarah.w@example.com',
    platform: 'Shopify',
    platform_buyer_id: 'SHOPIFY-004',
    blacklist_reason: 'Suspicious ordering pattern',
    blacklist_type: 'OTHER',
    risk_score: 50,
    blacklist_date: '2026-02-10',
    expiry_date: '2026-05-10',
    status: 'INACTIVE',
    evidence: 'Order history analysis',
    created_by: 'admin',
    trace_id: 'trace-004',
    created_at: '2026-02-10 11:00:00',
    updated_at: '2026-03-01 16:00:00',
  },
];

const BlacklistManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [blacklists, setBlacklists] = useState<BlacklistRecord[]>(MOCK_BLACKLISTS);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedBlacklist, setSelectedBlacklist] = useState<BlacklistRecord | null>(null);
  const [activeTab, setActiveTab] = useState('all');
  const [searchText, setSearchText] = useState('');
  const [platformFilter, setPlatformFilter] = useState<string>('');
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

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

  const fetchBlacklists = async () => {
    setLoading(true);
    try {
      setBlacklists(MOCK_BLACKLISTS);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async (values: any) => {
    setLoading(true);
    try {
      const newBlacklist: BlacklistRecord = {
        id: `${Date.now()}`,
        tenant_id: 'tenant-001',
        shop_id: 'shop-001',
        buyer_id: `buyer-${Date.now()}`,
        buyer_name: values.buyer_name,
        buyer_email: values.buyer_email,
        buyer_phone: values.buyer_phone,
        platform: values.platform,
        platform_buyer_id: values.platform_buyer_id,
        blacklist_reason: values.blacklist_reason,
        blacklist_type: values.blacklist_type,
        risk_score: values.risk_score,
        blacklist_date: dayjs().format('YYYY-MM-DD'),
        expiry_date: values.expiry_date ? values.expiry_date.format('YYYY-MM-DD') : undefined,
        status: 'ACTIVE',
        evidence: values.evidence,
        created_by: 'admin',
        trace_id: `trace-${Date.now()}`,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };

      setBlacklists([newBlacklist, ...blacklists]);
      message.success('Buyer added to blacklist successfully');
      setCreateModalVisible(false);
      form.resetFields();
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = async (values: any) => {
    if (!selectedBlacklist) return;

    setLoading(true);
    try {
      const updatedBlacklists = blacklists.map(bl => 
        bl.id === selectedBlacklist.id 
          ? {
              ...bl,
              buyer_name: values.buyer_name,
              buyer_email: values.buyer_email,
              buyer_phone: values.buyer_phone,
              blacklist_reason: values.blacklist_reason,
              blacklist_type: values.blacklist_type,
              risk_score: values.risk_score,
              expiry_date: values.expiry_date ? values.expiry_date.format('YYYY-MM-DD') : undefined,
              status: values.status,
              evidence: values.evidence,
              updated_at: new Date().toISOString(),
            }
          : bl
      );

      setBlacklists(updatedBlacklists);
      message.success('Blacklist record updated successfully');
      setEditModalVisible(false);
      form.resetFields();
      setSelectedBlacklist(null);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: 'Remove from Blacklist',
      content: 'Are you sure you want to remove this buyer from the blacklist?',
      okType: 'danger',
      onOk: () => {
        const updatedBlacklists = blacklists.map(bl => 
          bl.id === id ? { ...bl, status: 'INACTIVE' as const, updated_at: new Date().toISOString() } : bl
        );
        setBlacklists(updatedBlacklists);
        message.success('Buyer removed from blacklist');
      },
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('Please select records to delete');
      return;
    }

    Modal.confirm({
      title: 'Batch Remove from Blacklist',
      content: `Are you sure you want to remove ${selectedRowKeys.length} buyers from the blacklist?`,
      okType: 'danger',
      onOk: () => {
        const updatedBlacklists = blacklists.map(bl => 
          selectedRowKeys.includes(bl.id) ? { ...bl, status: 'INACTIVE' as const, updated_at: new Date().toISOString() } : bl
        );
        setBlacklists(updatedBlacklists);
        setSelectedRowKeys([]);
        message.success(`${selectedRowKeys.length} buyers removed from blacklist`);
      },
    });
  };

  const handleViewDetail = (blacklist: BlacklistRecord) => {
    setSelectedBlacklist(blacklist);
    setDetailModalVisible(true);
  };

  const handleEditClick = (blacklist: BlacklistRecord) => {
    setSelectedBlacklist(blacklist);
    form.setFieldsValue({
      buyer_name: blacklist.buyer_name,
      buyer_email: blacklist.buyer_email,
      buyer_phone: blacklist.buyer_phone,
      platform: blacklist.platform,
      platform_buyer_id: blacklist.platform_buyer_id,
      blacklist_reason: blacklist.blacklist_reason,
      blacklist_type: blacklist.blacklist_type,
      risk_score: blacklist.risk_score,
      expiry_date: blacklist.expiry_date ? dayjs(blacklist.expiry_date) : null,
      status: blacklist.status,
      evidence: blacklist.evidence,
    });
    setEditModalVisible(true);
  };

  const getFilteredBlacklists = () => {
    let filtered = blacklists;

    if (activeTab !== 'all') {
      filtered = filtered.filter(bl => bl.status === activeTab.toUpperCase());
    }

    if (searchText) {
      filtered = filtered.filter(bl => 
        bl.buyer_name.toLowerCase().includes(searchText.toLowerCase()) ||
        bl.buyer_email.toLowerCase().includes(searchText.toLowerCase()) ||
        bl.platform_buyer_id.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    if (platformFilter) {
      filtered = filtered.filter(bl => bl.platform === platformFilter);
    }

    if (typeFilter) {
      filtered = filtered.filter(bl => bl.blacklist_type === typeFilter);
    }

    return filtered;
  };

  const getRiskLevel = (score: number): { level: string; color: string } => {
    if (score >= 80) return { level: 'Critical', color: '#ff4d4f' };
    if (score >= 60) return { level: 'High', color: '#ff7a45' };
    if (score >= 40) return { level: 'Medium', color: '#faad14' };
    return { level: 'Low', color: '#52c41a' };
  };

  const columns: ColumnsType<BlacklistRecord> = [
    {
      title: 'Buyer Name',
      dataIndex: 'buyer_name',
      key: 'buyer_name',
      width: 150,
      render: (name: string, record: BlacklistRecord) => (
        <a onClick={() => handleViewDetail(record)}>{name}</a>
      ),
    },
    {
      title: 'Email',
      dataIndex: 'buyer_email',
      key: 'buyer_email',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
    },
    {
      title: 'Platform Buyer ID',
      dataIndex: 'platform_buyer_id',
      key: 'platform_buyer_id',
      width: 150,
    },
    {
      title: 'Type',
      dataIndex: 'blacklist_type',
      key: 'blacklist_type',
      width: 100,
      render: (type: string) => {
        const config = BLACKLIST_TYPES.find(t => t.value === type);
        return <Tag color={config?.color}>{type}</Tag>;
      },
    },
    {
      title: 'Risk Score',
      dataIndex: 'risk_score',
      key: 'risk_score',
      width: 120,
      render: (score: number) => {
        const { level, color } = getRiskLevel(score);
        return (
          <Tag color={color}>
            {score} - {level}
          </Tag>
        );
      },
      sorter: (a, b) => a.risk_score - b.risk_score,
    },
    {
      title: 'Blacklist Date',
      dataIndex: 'blacklist_date',
      key: 'blacklist_date',
      width: 120,
    },
    {
      title: 'Expiry Date',
      dataIndex: 'expiry_date',
      key: 'expiry_date',
      width: 120,
      render: (date: string) => {
        if (!date) return '-';
        const daysUntilExpiry = dayjs(date).diff(dayjs(), 'day');
        const isExpiringSoon = daysUntilExpiry > 0 && daysUntilExpiry <= 30;
        return (
          <Tooltip title={isExpiringSoon ? `Expires in ${daysUntilExpiry} days` : ''}>
            <span style={{ color: isExpiringSoon || daysUntilExpiry <= 0 ? '#ff4d4f' : undefined }}>
              {date}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = STATUS_CONFIG[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      render: (_, record: BlacklistRecord) => (
        <Space>
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          <Tooltip title="Edit">
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEditClick(record)} />
          </Tooltip>
          {record.status === 'ACTIVE' && (
            <Tooltip title="Remove">
              <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  const stats = {
    total: blacklists.length,
    active: blacklists.filter(bl => bl.status === 'ACTIVE').length,
    inactive: blacklists.filter(bl => bl.status === 'INACTIVE').length,
    expired: blacklists.filter(bl => bl.status === 'EXPIRED').length,
    highRisk: blacklists.filter(bl => bl.risk_score >= 60).length,
  };

  return (
    <div className="blacklist-manage-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic title="Total Blacklisted" value={stats.total} prefix={<UserOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Active" value={stats.active} valueStyle={{ color: '#ff4d4f' }} prefix={<StopOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Inactive" value={stats.inactive} valueStyle={{ color: '#8c8c8c' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="High Risk" value={stats.highRisk} valueStyle={{ color: '#ff7a45' }} prefix={<WarningOutlined />} />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Alert
              message="Blacklist Alert"
              description={`${stats.active} buyers are currently blacklisted. ${stats.highRisk} are high risk.`}
              type="error"
              showIcon
              icon={<WarningOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Blacklist Management" extra={
        <Space>
          {selectedRowKeys.length > 0 && (
            <Button danger icon={<DeleteOutlined />} onClick={handleBatchDelete}>
              Batch Remove ({selectedRowKeys.length})
            </Button>
          )}
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
            Add to Blacklist
          </Button>
        </Space>
      }>
        <div style={{ display: 'flex', marginBottom: 16, gap: 16 }}>
          <Input
            placeholder="Search by name, email, or platform buyer ID"
            prefix={<SearchOutlined />}
            style={{ width: 300 }}
            onChange={(e) => setSearchText(e.target.value)}
          />
          <Select
            placeholder="Filter by Platform"
            style={{ width: 150 }}
            onChange={setPlatformFilter}
            allowClear
          >
            {PLATFORMS.map(platform => (
              <Option key={platform} value={platform}>{platform}</Option>
            ))}
          </Select>
          <Select
            placeholder="Filter by Type"
            style={{ width: 150 }}
            onChange={setTypeFilter}
            allowClear
          >
            {BLACKLIST_TYPES.map(type => (
              <Option key={type.value} value={type.value}>{type.label}</Option>
            ))}
          </Select>
        </div>

        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="All" key="all" />
          <TabPane tab="Active" key="active" />
          <TabPane tab="Inactive" key="inactive" />
          <TabPane tab="Expired" key="expired" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={getFilteredBlacklists()}
          rowKey="id"
          loading={loading}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            getCheckboxProps: (record) => ({
              disabled: record.status !== 'ACTIVE',
            }),
          }}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="Add to Blacklist"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form form={form} layout="vertical" onFinish={handleCreate}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="platform" label="Platform" rules={[{ required: true }]}>
                <Select placeholder="Select Platform">
                  {PLATFORMS.map(platform => (
                    <Option key={platform} value={platform}>{platform}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="platform_buyer_id" label="Platform Buyer ID" rules={[{ required: true }]}>
                <Input placeholder="Enter platform buyer ID" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="buyer_name" label="Buyer Name" rules={[{ required: true }]}>
                <Input placeholder="Enter buyer name" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="buyer_email" label="Buyer Email" rules={[{ required: true, type: 'email' }]}>
                <Input placeholder="Enter buyer email" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="buyer_phone" label="Buyer Phone">
                <Input placeholder="Enter buyer phone" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="blacklist_type" label="Blacklist Type" rules={[{ required: true }]}>
                <Select placeholder="Select Type">
                  {BLACKLIST_TYPES.map(type => (
                    <Option key={type.value} value={type.value}>{type.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="blacklist_reason" label="Reason" rules={[{ required: true }]}>
            <TextArea rows={3} placeholder="Enter reason for blacklisting" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="risk_score" label="Risk Score" rules={[{ required: true }]}>
                <InputNumber min={0} max={100} style={{ width: '100%' }} placeholder="0-100" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="expiry_date" label="Expiry Date">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="evidence" label="Evidence">
            <Upload>
              <Button icon={<UploadOutlined />}>Upload Evidence</Button>
            </Upload>
          </Form.Item>

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setCreateModalVisible(false)} style={{ marginRight: 8 }}>Cancel</Button>
            <Button type="primary" htmlType="submit" loading={loading}>Add to Blacklist</Button>
          </div>
        </Form>
      </Modal>

      <Modal
        title="Edit Blacklist Record"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setSelectedBlacklist(null);
          form.resetFields();
        }}
        footer={null}
        width={700}
      >
        <Form form={form} layout="vertical" onFinish={handleEdit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="platform" label="Platform" rules={[{ required: true }]}>
                <Select placeholder="Select Platform">
                  {PLATFORMS.map(platform => (
                    <Option key={platform} value={platform}>{platform}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="platform_buyer_id" label="Platform Buyer ID" rules={[{ required: true }]}>
                <Input placeholder="Enter platform buyer ID" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="buyer_name" label="Buyer Name" rules={[{ required: true }]}>
                <Input placeholder="Enter buyer name" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="buyer_email" label="Buyer Email" rules={[{ required: true, type: 'email' }]}>
                <Input placeholder="Enter buyer email" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="buyer_phone" label="Buyer Phone">
                <Input placeholder="Enter buyer phone" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="blacklist_type" label="Blacklist Type" rules={[{ required: true }]}>
                <Select placeholder="Select Type">
                  {BLACKLIST_TYPES.map(type => (
                    <Option key={type.value} value={type.value}>{type.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="blacklist_reason" label="Reason" rules={[{ required: true }]}>
            <TextArea rows={3} placeholder="Enter reason for blacklisting" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="risk_score" label="Risk Score" rules={[{ required: true }]}>
                <InputNumber min={0} max={100} style={{ width: '100%' }} placeholder="0-100" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="expiry_date" label="Expiry Date">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="status" label="Status" rules={[{ required: true }]}>
                <Select placeholder="Select Status">
                  <Option value="ACTIVE">Active</Option>
                  <Option value="INACTIVE">Inactive</Option>
                  <Option value="EXPIRED">Expired</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="evidence" label="Evidence">
            <Upload>
              <Button icon={<UploadOutlined />}>Upload Evidence</Button>
            </Upload>
          </Form.Item>

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => {
              setEditModalVisible(false);
              setSelectedBlacklist(null);
              form.resetFields();
            }} style={{ marginRight: 8 }}>Cancel</Button>
            <Button type="primary" htmlType="submit" loading={loading}>Update Record</Button>
          </div>
        </Form>
      </Modal>

      <Modal
        title="Blacklist Record Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>Close</Button>,
          selectedBlacklist?.status === 'ACTIVE' && (
            <Button key="edit" type="primary" icon={<EditOutlined />} onClick={() => {
              setDetailModalVisible(false);
              handleEditClick(selectedBlacklist!);
            }}>
              Edit Record
            </Button>
          ),
        ]}
        width={700}
      >
        {selectedBlacklist && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Buyer Name" span={2}>{selectedBlacklist.buyer_name}</Descriptions.Item>
              <Descriptions.Item label="Email">{selectedBlacklist.buyer_email}</Descriptions.Item>
              <Descriptions.Item label="Phone">{selectedBlacklist.buyer_phone || '-'}</Descriptions.Item>
              <Descriptions.Item label="Platform">{selectedBlacklist.platform}</Descriptions.Item>
              <Descriptions.Item label="Platform Buyer ID">{selectedBlacklist.platform_buyer_id}</Descriptions.Item>
              <Descriptions.Item label="Blacklist Type">
                <Tag color={BLACKLIST_TYPES.find(t => t.value === selectedBlacklist.blacklist_type)?.color}>
                  {BLACKLIST_TYPES.find(t => t.value === selectedBlacklist.blacklist_type)?.label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Risk Score">
                <Tag color={getRiskLevel(selectedBlacklist.risk_score).color}>
                  {selectedBlacklist.risk_score} - {getRiskLevel(selectedBlacklist.risk_score).level}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={STATUS_CONFIG[selectedBlacklist.status].color} icon={STATUS_CONFIG[selectedBlacklist.status].icon}>
                  {STATUS_CONFIG[selectedBlacklist.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Blacklist Date">{selectedBlacklist.blacklist_date}</Descriptions.Item>
              <Descriptions.Item label="Expiry Date">{selectedBlacklist.expiry_date || '-'}</Descriptions.Item>
              <Descriptions.Item label="Reason" span={2}>{selectedBlacklist.blacklist_reason}</Descriptions.Item>
              <Descriptions.Item label="Evidence" span={2}>{selectedBlacklist.evidence || '-'}</Descriptions.Item>
              <Descriptions.Item label="Created By">{selectedBlacklist.created_by}</Descriptions.Item>
              <Descriptions.Item label="Created At">{selectedBlacklist.created_at}</Descriptions.Item>
            </Descriptions>
          </>
        )}
      </Modal>
    </div>
  );
};

export default BlacklistManage;
