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

const { Option } = Select;
const { Panel } = Collapse;
const { TextArea } = Input;

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: React.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',
          costs: [
            { id: 'c1', name: 'Platform Fee', type: 'PERCENTAGE', value: 15, currency: 'USD', applyTo: 'PLATFORM_FEE', description: 'Amazon referral fee' },
            { id: 'c2', name: 'FBA Fee', type: 'PER_UNIT', value: 3.5, currency: 'USD', applyTo: 'SHIPPING', description: 'Fulfillment fee' },
            { id: 'c3', name: 'Storage Fee', type: 'PER_UNIT', value: 0.5, currency: 'USD', applyTo: 'PRODUCT', description: 'Monthly storage' },
          ],
        },
        {
          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',
          costs: [
            { id: 'c4', name: 'Final Value Fee', type: 'PERCENTAGE', value: 12.5, currency: 'USD', applyTo: 'PLATFORM_FEE', description: 'eBay final value fee' },
            { id: 'c5', name: 'PayPal Fee', type: 'PERCENTAGE', value: 2.9, currency: 'USD', applyTo: 'ORDER', description: 'Payment processing fee' },
          ],
        },
        {
          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',
          costs: [
            { id: 'c6', name: 'Transaction Fee', type: 'PERCENTAGE', value: 2.0, currency: 'USD', applyTo: 'ORDER', description: 'Shopify transaction fee' },
            { id: 'c7', name: 'Payment Gateway', type: 'PERCENTAGE', value: 2.9, currency: 'USD', applyTo: 'ORDER', description: 'Credit card processing' },
          ],
        },
        {
          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',
          costs: [
            { id: 'c8', name: 'Shipping Surcharge', type: 'PERCENTAGE', value: 5, currency: 'USD', applyTo: 'SHIPPING', description: 'Heavy item shipping' },
            { id: 'c9', name: 'Insurance', type: 'PERCENTAGE', value: 1.5, currency: 'USD', applyTo: 'SHIPPING', description: 'Shipping insurance' },
          ],
        },
      ];
      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.costs);
    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 = (id: string, field: keyof CostItem, value: any) => {
    setCostItems(costItems.map(item => 
      item.id === id ? { ...item, [field]: value } : item
    ));
  };

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

  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: templates.filter(t => t.isDefault).length,
    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>
          {record.isDefault && <Tag color="gold">Default</Tag>}
        </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.costs.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>
          {!record.isDefault && (
            <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.id} size="small" style={{ marginBottom: 8 }}>
              <Row gutter={16}>
                <Col span={6}>
                  <Input
                    placeholder="Name"
                    value={item.name}
                    onChange={(e) => handleUpdateCostItem(item.id, 'name', e.target.value)}
                  />
                </Col>
                <Col span={4}>
                  <Select value={item.type} onChange={(v) => handleUpdateCostItem(item.id, 'type', v)}>
                    <Option value="FIXED">Fixed</Option>
                    <Option value="PERCENTAGE">Percentage</Option>
                    <Option value="PER_UNIT">Per Unit</Option>
                  </Select>
                </Col>
                <Col span={4}>
                  <InputNumber
                    style={{ width: '100%' }}
                    placeholder="Value"
                    value={item.value}
                    onChange={(v) => handleUpdateCostItem(item.id, 'value', v || 0)}
                  />
                </Col>
                <Col span={4}>
                  <Select value={item.applyTo} onChange={(v) => handleUpdateCostItem(item.id, 'applyTo', v)}>
                    <Option value="PRODUCT">Product</Option>
                    <Option value="SHIPPING">Shipping</Option>
                    <Option value="ORDER">Order</Option>
                    <Option value="PLATFORM_FEE">Platform Fee</Option>
                  </Select>
                </Col>
                <Col span={4}>
                  <Button danger icon={<DeleteOutlined />} onClick={() => handleRemoveCostItem(item.id)} />
                </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>
            <p><strong>Description:</strong> {viewingTemplate.description}</p>
            <Divider>Cost Items ({viewingTemplate.costs.length})</Divider>
            <Table
              dataSource={viewingTemplate.costs}
              rowKey="id"
              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: 'Apply To', dataIndex: 'applyTo', key: 'applyTo' },
                { title: 'Description', dataIndex: 'description', key: 'description' },
              ]}
            />
          </>
        )}
      </Modal>
    </div>
  );
};

export default CostTemplateConfig;
