import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Tag,
  Badge,
  message,
  Popconfirm,
  Tooltip,
  Row,
  Col,
  Statistic,
  Divider,
  Collapse,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  CalculatorOutlined,
  PercentageOutlined,
  DollarOutlined,
  SettingOutlined,
  Option,
  Panel,
  TextArea,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import { settingsDataSource, CostTemplate, CostItem } from '@/services/settingsDataSource';

const PLATFORM_LIST = ['AMAZON', 'EBAY', 'SHOPIFY', 'SHOPEE', 'LAZADA', 'ALIBABA', 'ALL'];
const CATEGORY_LIST = ['Electronics', 'Clothing', 'Home', 'Industrial', 'General'];

const COST_TYPE_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  fixed: { color: 'blue', text: 'Fixed', icon: <DollarOutlined /> },
  percentage: { color: 'green', text: 'Percentage', icon: <PercentageOutlined /> },
  per_unit: { color: 'orange', text: 'Per Unit', icon: <CalculatorOutlined /> },
};

const CostTemplateConfig: FC = () => {
  const [loading, setLoading] = useState(false);
  const [templates, setTemplates] = useState<CostTemplate[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<CostTemplate | null>(null);
  const [viewingTemplate, setViewingTemplate] = useState<CostTemplate | null>(null);
  const [costItems, setCostItems] = useState<CostItem[]>([]);
  const [form] = Form.useForm();

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

  const fetchTemplates = async () => {
    setLoading(true);
    try {
      const mockTemplates: CostTemplate[] = [
        {
          id: '1',
          name: 'Amazon US Standard',
          platform: 'AMAZON',
          category: 'Electronics',
          description: 'Standard cost template for Amazon US electronics',
          isDefault: true,
          isActive: true,
          createdAt: '2026-01-15',
          updatedAt: '2026-03-10',
          costItems: [
            { name: 'Platform Fee', type: 'percentage', value: 15, currency: 'USD' },
            { name: 'FBA Fee', type: 'fixed', value: 3.5, currency: 'USD' },
            { name: 'Storage Fee', type: 'fixed', value: 0.5, currency: 'USD' },
          ],
        },
        {
          id: '2',
          name: 'eBay Standard',
          platform: 'EBAY',
          category: 'General',
          description: 'Standard cost template for eBay',
          isDefault: true,
          isActive: true,
          createdAt: '2026-01-20',
          updatedAt: '2026-03-05',
          costItems: [
            { name: 'Final Value Fee', type: 'percentage', value: 12.5, currency: 'USD' },
            { name: 'PayPal Fee', type: 'percentage', value: 2.9, currency: 'USD' },
          ],
        },
        {
          id: '3',
          name: 'Shopify Standard',
          platform: 'SHOPIFY',
          category: 'General',
          description: 'Standard cost template for Shopify stores',
          isDefault: true,
          isActive: true,
          createdAt: '2026-02-01',
          updatedAt: '2026-03-15',
          costItems: [
            { name: 'Transaction Fee', type: 'percentage', value: 2.0, currency: 'USD' },
            { name: 'Payment Gateway', type: 'percentage', value: 2.9, currency: 'USD' },
          ],
        },
        {
          id: '4',
          name: 'Industrial Equipment',
          platform: 'ALL',
          category: 'Industrial',
          description: 'Cost template for industrial equipment across platforms',
          isDefault: false,
          isActive: true,
          createdAt: '2026-02-15',
          updatedAt: '2026-03-18',
          costItems: [
            { name: 'Shipping Surcharge', type: 'percentage', value: 5, currency: 'USD' },
            { name: 'Insurance', type: 'percentage', value: 1.5, currency: 'USD' },
          ],
        },
      ];
      setTemplates(mockTemplates);
    } catch (error) {
      message.error('Failed to load cost templates');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingTemplate(null);
    setCostItems([]);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: CostTemplate) => {
    setEditingTemplate(record);
    setCostItems(record.costItems || []);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleView = (record: CostTemplate) => {
    setViewingTemplate(record);
    setDetailModalVisible(true);
  };

  const handleDelete = (id: string) => {
    setTemplates(templates.filter(t => t.id !== id));
    message.success('Template deleted successfully');
  };

  const handleDuplicate = (record: CostTemplate) => {
    const newTemplate: CostTemplate = {
      ...record,
      id: `${Date.now()}`,
      name: `${record.name} (Copy)`,
      isDefault: false,
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0],
    };
    setTemplates([...templates, newTemplate]);
    message.success('Template duplicated successfully');
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const templateData: CostTemplate = {
        ...values,
        id: editingTemplate?.id || `${Date.now()}`,
        costs: costItems,
        createdAt: editingTemplate?.createdAt || new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0],
        isActive: true,
      };

      if (editingTemplate) {
        setTemplates(templates.map(t => t.id === editingTemplate.id ? templateData : t));
        message.success('Template updated successfully');
      } else {
        setTemplates([...templates, templateData]);
        message.success('Template created successfully');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const handleAddCostItem = () => {
    const newItem: CostItem = {
      id: `temp-${Date.now()}`,
      name: '',
      type: 'fixed',
      value: 0,
      currency: 'USD',
      applyTo: 'PRODUCT',
      description: '',
    };
    setCostItems([...costItems, newItem]);
  };

  const handleUpdateCostItem = (name: string, field: keyof CostItem, value: any) => {
    setCostItems(costItems.map(item => 
      item.name === name ? { ...item, [field]: value } : item
    ));
  };

  const handleRemoveCostItem = (name: string) => {
    setCostItems(costItems.filter(item => item.name !== name));
  };

  const handleSetDefault = (id: string) => {
    setTemplates(templates.map(t => ({
      ...t,
      isDefault: t.id === id,
    })));
    message.success('Default template updated');
  };

  const stats = {
    total: templates.length,
    active: templates.filter(t => t.isActive).length,
    defaults: 0,
    platforms: new Set(templates.map(t => t.platform)).size,
  };

  const columns: ColumnsType<CostTemplate> = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text, record) => (
        <Space>
          <a onClick={() => handleView(record)}>{text}</a>

        </Space>
      ),
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
      render: (platform) => <Tag color="blue">{platform}</Tag>,
    },
    {
      title: 'Category',
      dataIndex: 'category',
      key: 'category',
      width: 100,
    },
    {
      title: 'Cost Items',
      key: 'costCount',
      width: 100,
      render: (_, record) => <Badge count={record.costItems.length} style={{ backgroundColor: '#1890ff' }} />,
    },
    {
      title: 'Status',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      render: (active) => <Tag color={active ? 'success' : 'default'}>{active ? 'Active' : 'Inactive'}</Tag>,
    },
    {
      title: 'Updated',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 100,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="Edit">
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Tooltip title="Duplicate">
            <Button type="link" size="small" icon={<CopyOutlined />} onClick={() => handleDuplicate(record)} />
          </Tooltip>
          <Tooltip title="Set as Default">
            <Button type="link" size="small" onClick={() => handleSetDefault(record.id)}>
              Default
            </Button>
          </Tooltip>
          <Popconfirm title="Delete this template?" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="cost-template-config">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Templates" value={stats.total} prefix={<SettingOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Active" value={stats.active} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Defaults" value={stats.defaults} valueStyle={{ color: '#faad14' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Platforms" value={stats.platforms} valueStyle={{ color: '#1890ff' }} />
          </Card>
        </Col>
      </Row>

      <Card
        title="Cost Template Configuration"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            Create Template
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={templates}
          rowKey="id"
          loading={loading}
          scroll={{ x: 900 }}
          pagination={{ showSizeChanger: true, showTotal: (total) => `Total ${total} templates` }}
        />
      </Card>

      <Modal
        title={editingTemplate ? 'Edit Cost Template' : 'Create Cost Template'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="Template Name" rules={[{ required: true }]}>
                <Input placeholder="Enter template name" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="platform" label="Platform" rules={[{ required: true }]}>
                <Select placeholder="Select platform">
                  {PLATFORM_LIST.map(p => (
                    <Option key={p} value={p}>{p}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="category" label="Category" rules={[{ required: true }]}>
                <Select placeholder="Select category">
                  {CATEGORY_LIST.map(c => (
                    <Option key={c} value={c}>{c}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="description" label="Description">
            <TextArea rows={2} placeholder="Enter description" />
          </Form.Item>
          <Form.Item name="isDefault" label="Set as Default" valuePropName="checked">
            <Switch />
          </Form.Item>

          <Divider>Cost Items</Divider>

          <div style={{ marginBottom: 16 }}>
            <Button icon={<PlusOutlined />} onClick={handleAddCostItem}>
              Add Cost Item
            </Button>
          </div>

          {costItems.map((item, index) => (
            <Card key={item.name} size="small" style={{ marginBottom: 8 }}>
              <Row gutter={16}>
                <Col span={6}>
                  <Input
                    placeholder="Name"
                    value={item.name}
                    onChange={(e) => handleUpdateCostItem(item.name, 'name', e.target.value)}
                  />
                </Col>
                <Col span={4}>
                  <Select value={item.type} onChange={(v) => handleUpdateCostItem(item.name, 'type', v)}>
                    <Option value="fixed">Fixed</Option>
                    <Option value="percentage">Percentage</Option>
                  </Select>
                </Col>
                <Col span={4}>
                  <InputNumber
                    style={{ width: '100%' }}
                    placeholder="Value"
                    value={item.value}
                    onChange={(v) => handleUpdateCostItem(item.name, 'value', v || 0)}
                  />
                </Col>
                <Col span={4}>
                  <Select value={item.currency} onChange={(v) => handleUpdateCostItem(item.name, 'currency', v)}>
                    <Option value="USD">USD</Option>
                    <Option value="CNY">CNY</Option>
                    <Option value="GBP">GBP</Option>
                    <Option value="EUR">EUR</Option>
                  </Select>
                </Col>
                <Col span={4}>
                  <Button danger icon={<DeleteOutlined />} onClick={() => handleRemoveCostItem(item.name)} />
                </Col>
              </Row>
            </Card>
          ))}
        </Form>
      </Modal>

      <Modal
        title={`Template: ${viewingTemplate?.name}`}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={700}
      >
        {viewingTemplate && (
          <>
            <Row gutter={16}>
              <Col span={8}>
                <p><strong>Platform:</strong> <Tag color="blue">{viewingTemplate.platform}</Tag></p>
              </Col>
              <Col span={8}>
                <p><strong>Category:</strong> {viewingTemplate.category}</p>
              </Col>
              <Col span={8}>
                <p><strong>Status:</strong> <Tag color={viewingTemplate.isActive ? 'success' : 'default'}>{viewingTemplate.isActive ? 'Active' : 'Inactive'}</Tag></p>
              </Col>
            </Row>
            <Divider>Cost Items ({viewingTemplate.costItems.length})</Divider>
            <Table
              dataSource={viewingTemplate.costItems}
              rowKey="name"
              size="small"
              pagination={false}
              columns={[
                { title: 'Name', dataIndex: 'name', key: 'name' },
                { title: 'Type', dataIndex: 'type', key: 'type', render: (t) => <Tag color={COST_TYPE_CONFIG[t].color}>{COST_TYPE_CONFIG[t].text}</Tag> },
                { title: 'Value', dataIndex: 'value', key: 'value', render: (v, r) => r.type === 'percentage' ? `${v}%` : `$${v}` },
                { title: 'Currency', dataIndex: 'currency', key: 'currency' },
              ]}
            />
          </>
        )}
      </Modal>
    </div>
  );
};

export default CostTemplateConfig;
