import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  message,
  Popconfirm,
  Badge,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  EyeOutlined,
  DollarOutlined,
  CalendarOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { marketingDataSource, Ad } from '@/services/marketingDataSource';

const { Option } = Select;
const { RangePicker } = DatePicker;

type AdPlatform = 'AMAZON' | 'EBAY' | 'SHOPEE' | 'TIKTOK';
type AdPlanStatus = 'DRAFT' | 'ACTIVE' | 'PAUSED' | 'COMPLETED' | 'PENDING_REVIEW';

interface AdPlan {
  id: string;
  tenant_id: string;
  shop_id: string;
  name: string;
  platform: AdPlatform;
  budget: number;
  daily_budget?: number;
  start_date?: string;
  end_date?: string;
  status: AdPlanStatus;
  target_audience?: string;
  keywords?: string[];
  created_at: string;
  updated_at: string;
}

interface CreateAdPlanParams {
  name: string;
  platform: AdPlatform;
  budget: number;
  dailyBudget?: number;
  startDate?: string;
  endDate?: string;
  targetAudience?: string;
  keywords?: string[];
}

const PLATFORM_COLORS: Record<AdPlatform, string> = {
  AMAZON: 'orange',
  EBAY: 'blue',
  SHOPEE: 'red',
  TIKTOK: 'cyan',
};

const STATUS_COLORS: Record<AdPlanStatus, string> = {
  DRAFT: 'default',
  ACTIVE: 'green',
  PAUSED: 'orange',
  COMPLETED: 'blue',
  PENDING_REVIEW: 'gold',
};

const STATUS_ICONS: Record<AdPlanStatus, React.ReactNode> = {
  DRAFT: <ClockCircleOutlined />,
  ACTIVE: <CheckCircleOutlined />,
  PAUSED: <PauseCircleOutlined />,
  COMPLETED: <CheckCircleOutlined />,
  PENDING_REVIEW: <WarningOutlined />,
};

const MOCK_AD_PLANS: AdPlan[] = [
  {
    id: 'ADP-001',
    tenant_id: 'T001',
    shop_id: 'S001',
    name: 'Summer Sale Campaign',
    platform: 'AMAZON',
    budget: 5000,
    daily_budget: 200,
    start_date: '2026-06-01',
    end_date: '2026-06-30',
    status: 'ACTIVE',
    target_audience: 'Electronics enthusiasts',
    keywords: ['electronics', 'gadgets', 'tech'],
    created_at: '2026-05-15T10:00:00Z',
    updated_at: '2026-05-15T10:00:00Z',
  },
  {
    id: 'ADP-002',
    tenant_id: 'T001',
    shop_id: 'S001',
    name: 'New Product Launch',
    platform: 'SHOPEE',
    budget: 15000,
    daily_budget: 500,
    start_date: '2026-07-01',
    end_date: '2026-07-31',
    status: 'PENDING_REVIEW',
    target_audience: 'Young professionals',
    keywords: ['lifestyle', 'trending'],
    created_at: '2026-05-20T14:30:00Z',
    updated_at: '2026-05-20T14:30:00Z',
  },
  {
    id: 'ADP-003',
    tenant_id: 'T001',
    shop_id: 'S002',
    name: 'Brand Awareness Q3',
    platform: 'TIKTOK',
    budget: 8000,
    daily_budget: 300,
    start_date: '2026-07-01',
    end_date: '2026-09-30',
    status: 'DRAFT',
    created_at: '2026-05-22T09:15:00Z',
    updated_at: '2026-05-22T09:15:00Z',
  },
];

export const AdPlanPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [adPlans, setAdPlans] = useState<AdPlan[]>(MOCK_AD_PLANS);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<AdPlan | null>(null);
  const [editingPlan, setEditingPlan] = useState<AdPlan | null>(null);
  const [filterStatus, setFilterStatus] = useState<AdPlanStatus | 'all'>('all');
  const [filterPlatform, setFilterPlatform] = useState<AdPlatform | 'all'>('all');

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

  const loadAdPlans = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setAdPlans(MOCK_AD_PLANS);
    } catch (error) {
      message.error('Failed to load ad plans');
    } finally {
      setLoading(false);
    }
  };

  const handleCreatePlan = async (values: CreateAdPlanParams) => {
    setLoading(true);
    try {
      const newPlan: AdPlan = {
        id: `ADP-${Date.now()}`,
        tenant_id: 'T001',
        shop_id: 'S001',
        name: values.name,
        platform: values.platform,
        budget: values.budget,
        daily_budget: values.dailyBudget,
        start_date: values.startDate,
        end_date: values.endDate,
        status: values.budget >= 10000 ? 'PENDING_REVIEW' : 'DRAFT',
        target_audience: values.targetAudience,
        keywords: values.keywords?.filter(k => k.trim()),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };

      setAdPlans([...adPlans, newPlan]);
      setModalVisible(false);
      form.resetFields();
      message.success('Ad plan created successfully');
      
      if (newPlan.status === 'PENDING_REVIEW') {
        message.warning('Budget exceeds $10,000, requires manual review');
      }
    } catch (error) {
      message.error('Failed to create ad plan');
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateStatus = async (planId: string, newStatus: AdPlanStatus) => {
    setLoading(true);
    try {
      setAdPlans(adPlans.map(plan => 
        plan.id === planId 
          ? { ...plan, status: newStatus, updated_at: new Date().toISOString() }
          : plan
      ));
      message.success(`Ad plan status updated to ${newStatus}`);
    } catch (error) {
      message.error('Failed to update status');
    } finally {
      setLoading(false);
    }
  };

  const handleDeletePlan = async (planId: string) => {
    setLoading(true);
    try {
      setAdPlans(adPlans.filter(plan => plan.id !== planId));
      message.success('Ad plan deleted successfully');
    } catch (error) {
      message.error('Failed to delete ad plan');
    } finally {
      setLoading(false);
    }
  };

  const openCreateModal = () => {
    setEditingPlan(null);
    form.resetFields();
    setModalVisible(true);
  };

  const openEditModal = (plan: AdPlan) => {
    setEditingPlan(plan);
    form.setFieldsValue({
      name: plan.name,
      platform: plan.platform,
      budget: plan.budget,
      dailyBudget: plan.daily_budget,
      targetAudience: plan.target_audience,
      keywords: plan.keywords,
    });
    setModalVisible(true);
  };

  const openDetailModal = (plan: AdPlan) => {
    setSelectedPlan(plan);
    setDetailModalVisible(true);
  };

  const filteredPlans = adPlans.filter(plan => {
    if (filterStatus !== 'all' && plan.status !== filterStatus) return false;
    if (filterPlatform !== 'all' && plan.platform !== filterPlatform) return false;
    return true;
  });

  const columns: ColumnsType<AdPlan> = [
    {
      title: 'Plan ID',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      render: (id: string) => <code>{id}</code>,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
      render: (platform: AdPlatform) => (
        <Tag color={PLATFORM_COLORS[platform]}>{platform}</Tag>
      ),
    },
    {
      title: 'Budget',
      dataIndex: 'budget',
      key: 'budget',
      width: 120,
      render: (budget: number) => (
        <strong style={{ color: '#1890ff' }}>${budget.toLocaleString()}</strong>
      ),
    },
    {
      title: 'Daily Budget',
      dataIndex: 'daily_budget',
      key: 'daily_budget',
      width: 120,
      render: (budget?: number) => budget ? `$${budget.toLocaleString()}` : '-',
    },
    {
      title: 'Duration',
      key: 'duration',
      width: 180,
      render: (_, record) => (
        <Space>
          <CalendarOutlined />
          <span>
            {record.start_date ? dayjs(record.start_date).format('YYYY-MM-DD') : '-'}
            {' ~ '}
            {record.end_date ? dayjs(record.end_date).format('YYYY-MM-DD') : '-'}
          </span>
        </Space>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      render: (status: AdPlanStatus) => (
        <Tag color={STATUS_COLORS[status]} icon={STATUS_ICONS[status]}>
          {status.replace('_', ' ')}
        </Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="View Details">
            <Button 
              type="link" 
              size="small" 
              icon={<EyeOutlined />}
              onClick={() => openDetailModal(record)}
            />
          </Tooltip>
          {record.status === 'DRAFT' && (
            <Tooltip title="Activate">
              <Button 
                type="link" 
                size="small" 
                icon={<PlayCircleOutlined />}
                onClick={() => handleUpdateStatus(record.id, 'ACTIVE')}
              />
            </Tooltip>
          )}
          {record.status === 'ACTIVE' && (
            <Tooltip title="Pause">
              <Button 
                type="link" 
                size="small" 
                icon={<PauseCircleOutlined />}
                onClick={() => handleUpdateStatus(record.id, 'PAUSED')}
              />
            </Tooltip>
          )}
          {record.status === 'PAUSED' && (
            <Tooltip title="Resume">
              <Button 
                type="link" 
                size="small" 
                icon={<PlayCircleOutlined />}
                onClick={() => handleUpdateStatus(record.id, 'ACTIVE')}
              />
            </Tooltip>
          )}
          {record.status === 'PENDING_REVIEW' && (
            <Tooltip title="Approve">
              <Button 
                type="link" 
                size="small" 
                style={{ color: '#52c41a' }}
                onClick={() => handleUpdateStatus(record.id, 'ACTIVE')}
              >
                Approve
              </Button>
            </Tooltip>
          )}
          <Tooltip title="Edit">
            <Button 
              type="link" 
              size="small" 
              icon={<EditOutlined />}
              onClick={() => openEditModal(record)}
              disabled={record.status === 'ACTIVE'}
            />
          </Tooltip>
          <Popconfirm
            title="Delete this ad plan?"
            onConfirm={() => handleDeletePlan(record.id)}
            okText="Yes"
            cancelText="No"
          >
            <Tooltip title="Delete">
              <Button 
                type="link" 
                size="small" 
                danger 
                icon={<DeleteOutlined />}
                disabled={record.status === 'ACTIVE'}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const totalBudget = adPlans.reduce((sum, plan) => sum + plan.budget, 0);
  const activePlans = adPlans.filter(p => p.status === 'ACTIVE').length;
  const pendingReview = adPlans.filter(p => p.status === 'PENDING_REVIEW').length;

  return (
    <div className="ad-plan-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Ad Plans"
              value={adPlans.length}
              suffix="plans"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Budget"
              value={totalBudget}
              precision={0}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Active Plans"
              value={activePlans}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Pending Review"
              value={pendingReview}
              valueStyle={{ color: pendingReview > 0 ? '#faad14' : '#52c41a' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card 
        title="Ad Plan Management"
        extra={
          <Space>
            <Select 
              value={filterStatus} 
              onChange={setFilterStatus}
              style={{ width: 150 }}
            >
              <Option value="all">All Status</Option>
              <Option value="DRAFT">Draft</Option>
              <Option value="ACTIVE">Active</Option>
              <Option value="PAUSED">Paused</Option>
              <Option value="PENDING_REVIEW">Pending Review</Option>
              <Option value="COMPLETED">Completed</Option>
            </Select>
            <Select 
              value={filterPlatform} 
              onChange={setFilterPlatform}
              style={{ width: 120 }}
            >
              <Option value="all">All Platforms</Option>
              <Option value="AMAZON">Amazon</Option>
              <Option value="EBAY">eBay</Option>
              <Option value="SHOPEE">Shopee</Option>
              <Option value="TIKTOK">TikTok</Option>
            </Select>
            <Button type="primary" icon={<PlusOutlined />} onClick={openCreateModal}>
              Create Plan
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredPlans}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1300 }}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} plans`,
          }}
        />
      </Card>

      <Modal
        title={editingPlan ? 'Edit Ad Plan' : 'Create Ad Plan'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingPlan(null);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreatePlan}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="Plan Name"
                rules={[{ required: true, message: 'Please enter plan name' }]}
              >
                <Input placeholder="Enter plan name" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="platform"
                label="Platform"
                rules={[{ required: true, message: 'Please select platform' }]}
              >
                <Select placeholder="Select platform">
                  <Option value="AMAZON">Amazon</Option>
                  <Option value="EBAY">eBay</Option>
                  <Option value="SHOPEE">Shopee</Option>
                  <Option value="TIKTOK">TikTok</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="budget"
                label="Total Budget ($)"
                rules={[{ required: true, message: 'Please enter budget' }]}
              >
                <InputNumber
                  min={1}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="Enter total budget"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="dailyBudget"
                label="Daily Budget ($)"
              >
                <InputNumber
                  min={1}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="Enter daily budget"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startDate"
                label="Start Date"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endDate"
                label="End Date"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="targetAudience"
            label="Target Audience"
          >
            <Input placeholder="Enter target audience" />
          </Form.Item>
          <Form.Item
            name="keywords"
            label="Keywords"
          >
            <Select
              mode="tags"
              placeholder="Add keywords"
              tokenSeparators={[',']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                {editingPlan ? 'Update' : 'Create'}
              </Button>
              <Button onClick={() => {
                setModalVisible(false);
                setEditingPlan(null);
                form.resetFields();
              }}>
                Cancel
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Ad Plan Details"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setSelectedPlan(null);
        }}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={700}
      >
        {selectedPlan && (
          <div>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Card size="small" title="Basic Info">
                  <p><strong>Plan ID:</strong> <code>{selectedPlan.id}</code></p>
                  <p><strong>Name:</strong> {selectedPlan.name}</p>
                  <p>
                    <strong>Platform:</strong>{' '}
                    <Tag color={PLATFORM_COLORS[selectedPlan.platform]}>
                      {selectedPlan.platform}
                    </Tag>
                  </p>
                  <p>
                    <strong>Status:</strong>{' '}
                    <Tag color={STATUS_COLORS[selectedPlan.status]} icon={STATUS_ICONS[selectedPlan.status]}>
                      {selectedPlan.status.replace('_', ' ')}
                    </Tag>
                  </p>
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title="Budget & Duration">
                  <p><strong>Total Budget:</strong> ${selectedPlan.budget.toLocaleString()}</p>
                  <p><strong>Daily Budget:</strong> {selectedPlan.daily_budget ? `$${selectedPlan.daily_budget.toLocaleString()}` : '-'}</p>
                  <p><strong>Start Date:</strong> {selectedPlan.start_date || '-'}</p>
                  <p><strong>End Date:</strong> {selectedPlan.end_date || '-'}</p>
                </Card>
              </Col>
            </Row>
            {selectedPlan.target_audience && (
              <Card size="small" title="Target Audience" style={{ marginTop: 16 }}>
                <p>{selectedPlan.target_audience}</p>
              </Card>
            )}
            {selectedPlan.keywords && selectedPlan.keywords.length > 0 && (
              <Card size="small" title="Keywords" style={{ marginTop: 16 }}>
                <Space wrap>
                  {selectedPlan.keywords.map((keyword, index) => (
                    <Tag key={index}>{keyword}</Tag>
                  ))}
                </Space>
              </Card>
            )}
            <Card size="small" title="Timestamps" style={{ marginTop: 16 }}>
              <p><strong>Created:</strong> {dayjs(selectedPlan.created_at).format('YYYY-MM-DD HH:mm:ss')}</p>
              <p><strong>Updated:</strong> {dayjs(selectedPlan.updated_at).format('YYYY-MM-DD HH:mm:ss')}</p>
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdPlanPage;
