import React, { useEffect, useState } from 'react';
import {
  Button, Card, Form, Input, message, Modal, Popconfirm, Space, Switch, Table, Tag, Typography, Dropdown, Select,
} from 'antd';
import {
  AppstoreOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownOutlined, MinusCircleOutlined,
  ShoppingCartOutlined, BookOutlined, HomeOutlined, FireOutlined, RocketOutlined, SkinOutlined,
  CompassOutlined, HeartOutlined, CarOutlined, CameraOutlined, CloudOutlined, StarOutlined,
  TrophyOutlined, ThunderboltOutlined, BulbOutlined, CoffeeOutlined, CrownOutlined, DashboardOutlined,
  FlagOutlined, GlobalOutlined, GiftOutlined, LaptopOutlined, MobileOutlined, MonitorOutlined,
  PayCircleOutlined, PictureOutlined, PlayCircleOutlined, SafetyOutlined,
  ShoppingOutlined, SmileOutlined, SoundOutlined, TagOutlined, TeamOutlined,
  ToolOutlined, TruckOutlined, VideoCameraOutlined, WalletOutlined, BankOutlined,
  BuildOutlined, ExperimentOutlined, HighlightOutlined, IdcardOutlined,
  MedicineBoxOutlined, ReadOutlined, RestOutlined, SketchOutlined, SolutionOutlined,
} from '@ant-design/icons';
import { getIndustryConfigs, saveIndustryConfig, deleteIndustryConfig } from '../api';

interface OptionGroup {
  name: string;
  options: string[];
}

interface IndustryItem {
  id: string;
  key: string;
  label: string;
  icon: string;
  description: string;
  skills: string;
  optionGroups: OptionGroup[];
  isActive: boolean;
  sortOrder: number;
}

// Icon library for industries
const ICON_OPTIONS: { name: string; label: string; component: React.ReactNode }[] = [
  { name: 'ShoppingCartOutlined', label: '购物', component: <ShoppingCartOutlined /> },
  { name: 'BookOutlined', label: '书籍', component: <BookOutlined /> },
  { name: 'HomeOutlined', label: '房产', component: <HomeOutlined /> },
  { name: 'FireOutlined', label: '火', component: <FireOutlined /> },
  { name: 'RocketOutlined', label: '科技', component: <RocketOutlined /> },
  { name: 'SkinOutlined', label: '时尚', component: <SkinOutlined /> },
  { name: 'CompassOutlined', label: '指南', component: <CompassOutlined /> },
  { name: 'HeartOutlined', label: '健康', component: <HeartOutlined /> },
  { name: 'CarOutlined', label: '汽车', component: <CarOutlined /> },
  { name: 'CameraOutlined', label: '相机', component: <CameraOutlined /> },
  { name: 'CloudOutlined', label: '云', component: <CloudOutlined /> },
  { name: 'StarOutlined', label: '星', component: <StarOutlined /> },
  { name: 'TrophyOutlined', label: '奖杯', component: <TrophyOutlined /> },
  { name: 'ThunderboltOutlined', label: '闪电', component: <ThunderboltOutlined /> },
  { name: 'BulbOutlined', label: '灯泡', component: <BulbOutlined /> },
  { name: 'CoffeeOutlined', label: '咖啡', component: <CoffeeOutlined /> },
  { name: 'CrownOutlined', label: '皇冠', component: <CrownOutlined /> },
  { name: 'DashboardOutlined', label: '仪表', component: <DashboardOutlined /> },
  { name: 'FlagOutlined', label: '旗帜', component: <FlagOutlined /> },
  { name: 'GlobalOutlined', label: '全球', component: <GlobalOutlined /> },
  { name: 'GiftOutlined', label: '礼物', component: <GiftOutlined /> },
  { name: 'LaptopOutlined', label: '笔记本', component: <LaptopOutlined /> },
  { name: 'MobileOutlined', label: '手机', component: <MobileOutlined /> },
  { name: 'MonitorOutlined', label: '显示器', component: <MonitorOutlined /> },
  { name: 'PayCircleOutlined', label: '支付', component: <PayCircleOutlined /> },
  { name: 'PictureOutlined', label: '图片', component: <PictureOutlined /> },
  { name: 'PlayCircleOutlined', label: '播放', component: <PlayCircleOutlined /> },
  { name: 'SafetyOutlined', label: '安全', component: <SafetyOutlined /> },
  { name: 'ShoppingOutlined', label: '商店', component: <ShoppingOutlined /> },
  { name: 'SmileOutlined', label: '笑脸', component: <SmileOutlined /> },
  { name: 'SoundOutlined', label: '声音', component: <SoundOutlined /> },
  { name: 'TagOutlined', label: '标签', component: <TagOutlined /> },
  { name: 'TeamOutlined', label: '团队', component: <TeamOutlined /> },
  { name: 'ToolOutlined', label: '工具', component: <ToolOutlined /> },
  { name: 'TruckOutlined', label: '物流', component: <TruckOutlined /> },
  { name: 'VideoCameraOutlined', label: '视频', component: <VideoCameraOutlined /> },
  { name: 'WalletOutlined', label: '钱包', component: <WalletOutlined /> },
  { name: 'BankOutlined', label: '银行', component: <BankOutlined /> },
  { name: 'BuildOutlined', label: '建筑', component: <BuildOutlined /> },
  { name: 'ExperimentOutlined', label: '实验', component: <ExperimentOutlined /> },
  { name: 'HighlightOutlined', label: '高亮', component: <HighlightOutlined /> },
  { name: 'IdcardOutlined', label: '名片', component: <IdcardOutlined /> },
  { name: 'MedicineBoxOutlined', label: '医药', component: <MedicineBoxOutlined /> },
  { name: 'ReadOutlined', label: '阅读', component: <ReadOutlined /> },
  { name: 'RestOutlined', label: '休息', component: <RestOutlined /> },
  { name: 'SketchOutlined', label: '钻石', component: <SketchOutlined /> },
  { name: 'SolutionOutlined', label: '方案', component: <SolutionOutlined /> },
];

const iconMap: Record<string, React.ReactNode> = Object.fromEntries(
  ICON_OPTIONS.map(o => [o.name, o.component])
);

function getIconComponent(name: string): React.ReactNode {
  return iconMap[name] || <AppstoreOutlined />;
}

// Parse skills JSON into { skillItems, optionGroups }
function parseSkills(raw: string | any[]): { skillItems: { key: string; label: string }[]; optionGroups: OptionGroup[] } {
  try {
    const arr = typeof raw === 'string' ? JSON.parse(raw) : raw;
    if (!Array.isArray(arr)) return { skillItems: [], optionGroups: [] };
    const skillItems: { key: string; label: string }[] = [];
    const optionGroups: OptionGroup[] = [];
    for (const item of arr) {
      if (item && item.type === 'option_group' && item.name && Array.isArray(item.options)) {
        optionGroups.push({ name: item.name, options: item.options });
      } else if (item && item.key && item.label) {
        skillItems.push({ key: item.key, label: item.label });
      }
    }
    return { skillItems, optionGroups };
  } catch {
    return { skillItems: [], optionGroups: [] };
  }
}

// Icon Picker Component
const IconPicker: React.FC<{ value?: string; onChange?: (v: string) => void }> = ({ value, onChange }) => {
  const selected = ICON_OPTIONS.find(o => o.name === value);
  return (
    <Dropdown
      trigger={['click']}
      dropdownRender={() => (
        <div style={{
          background: '#fff', borderRadius: 12, padding: 12, width: 360,
          boxShadow: '0 12px 40px rgba(0,0,0,0.15)', border: '1px solid #f0f0f5',
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 4 }}>
            {ICON_OPTIONS.map(opt => (
              <div key={opt.name} onMouseDown={e => { e.preventDefault(); e.stopPropagation(); onChange?.(opt.name); }} title={opt.label} style={{
                width: 40, height: 40, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: 'pointer', fontSize: 18, transition: 'all 0.15s',
                background: value === opt.name ? '#6366f1' : 'transparent',
                color: value === opt.name ? '#fff' : '#64748b',
                border: value === opt.name ? 'none' : '1px solid transparent',
              }}
                onMouseEnter={e => { if (value !== opt.name) e.currentTarget.style.background = '#f1f5f9'; }}
                onMouseLeave={e => { if (value !== opt.name) e.currentTarget.style.background = 'transparent'; }}
              >
                {opt.component}
              </div>
            ))}
          </div>
        </div>
      )}
    >
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px',
        borderRadius: 8, border: '1px solid #d9d9d9', cursor: 'pointer', height: 40,
      }}>
        {value ? (
          <>
            <span style={{ fontSize: 18, color: '#6366f1' }}>{getIconComponent(value)}</span>
            <span style={{ color: '#64748b', fontSize: 13 }}>{selected?.label || value}</span>
          </>
        ) : (
          <span style={{ color: '#bfbfbf', fontSize: 13 }}>选择图标</span>
        )}
        <DownOutlined style={{ fontSize: 10, color: '#bfbfbf', marginLeft: 'auto' }} />
      </div>
    </Dropdown>
  );
};

const AdminIndustries: React.FC = () => {
  const [industries, setIndustries] = useState<IndustryItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [modal, setModal] = useState<{ open: boolean; item: IndustryItem | null }>({ open: false, item: null });
  const [form] = Form.useForm();

  const load = async () => {
    setLoading(true);
    try {
      const data = await getIndustryConfigs();
      setIndustries(data.map((item: any) => {
        const { skillItems, optionGroups } = parseSkills(item.skills);
        return {
          id: item.id,
          key: item.key,
          label: item.label,
          icon: item.icon || '',
          description: item.description || '',
          skills: JSON.stringify(skillItems),
          optionGroups,
          isActive: item.is_active ?? item.isActive ?? true,
          sortOrder: item.sort_order ?? item.sortOrder ?? 0,
        };
      }));
    } catch {
      message.error('加载行业配置失败');
    } finally {
      setLoading(false);
    }
  };

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

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);

      // Build skills array: skill items + option groups
      const skillsArr: any[] = [];
      if (values.skills_wentutujie?.trim()) {
        skillsArr.push({ type: 'skill', key: '文图理解生成视频提示词', label: values.skills_wentutujie.trim() });
      }
      if (values.skills_wentutujie_image?.trim()) {
        skillsArr.push({ type: 'skill', key: '文图理解生成图片提示词', label: values.skills_wentutujie_image.trim() });
      }
      // Add option groups
      const groups: OptionGroup[] = (values.optionGroups || [])
        .filter((g: any) => g?.name?.trim())
        .map((g: any) => ({
          name: g.name.trim(),
          options: (g.options || []).filter((o: string) => o?.trim()),
        }))
        .filter((g: OptionGroup) => g.options.length > 0);
      for (const g of groups) {
        skillsArr.push({ type: 'option_group', name: g.name, options: g.options });
      }

      const payload: any = {
        key: values.key,
        label: values.label,
        icon: values.icon || '',
        description: values.description || '',
        skills: skillsArr,
        is_active: values.is_active ?? true,
        sort_order: values.sort_order ?? 0,
      };
      if (modal.item?.id) {
        await saveIndustryConfig({ id: modal.item.id, ...payload });
        message.success('已更新');
      } else {
        await saveIndustryConfig(payload);
        message.success('已添加');
      }
      setModal({ open: false, item: null });
      form.resetFields();
      load();
    } catch (e: any) {
      if (e?.errorFields) return;
      message.error(e?.message || '保存失败');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteIndustryConfig(id);
      message.success('已删除');
      load();
    } catch (e: any) {
      message.error(e?.message || '删除失败');
    }
  };

  const openEdit = (item?: IndustryItem) => {
    setModal({ open: true, item: item || null });
    let wentutujie = '';
    let wentutujieImage = '';
    let optionGroups: OptionGroup[] = [];
    if (item) {
      // Parse skills for 文图理解 video and image prompts
      try {
        const arr = JSON.parse(item.skills);
        if (Array.isArray(arr)) {
          for (const s of arr) {
            if (s.key === '文图理解生成视频提示词' || s.key === '文图理解') { wentutujie = s.label || ''; }
            if (s.key === '文图理解生成图片提示词') { wentutujieImage = s.label || ''; }
          }
        }
      } catch { /* ignore */ }
      optionGroups = item.optionGroups.length > 0 ? item.optionGroups : [{ name: '', options: [] }];
    }
    if (item) {
      form.setFieldsValue({
        key: item.key,
        label: item.label,
        icon: item.icon || '',
        description: item.description,
        skills_wentutujie: wentutujie,
        skills_wentutujie_image: wentutujieImage,
        optionGroups,
        is_active: item.isActive,
        sort_order: item.sortOrder,
      });
    } else {
      form.resetFields();
      form.setFieldsValue({ is_active: true, sort_order: 0, optionGroups: [{ name: '', options: [] }] });
    }
  };

  const columns = [
    {
      title: '行业', key: 'industry', width: 180,
      render: (_: any, r: IndustryItem) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, background: '#f1f5f9',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18, color: '#6366f1', flexShrink: 0,
          }}>
            {getIconComponent(r.icon)}
          </div>
          <div>
            <Typography.Text strong>{r.label}</Typography.Text>
            <div style={{ color: '#94a3b8', fontSize: 12 }}>{r.key}</div>
          </div>
        </div>
      ),
    },
    { title: '描述', dataIndex: 'description', ellipsis: true },
    {
      title: '选项配置', key: 'optionGroups', width: 260,
      render: (_: any, r: IndustryItem) => {
        if (!r.optionGroups || r.optionGroups.length === 0) {
          return <Typography.Text style={{ fontSize: 12, color: '#cbd5e1' }}>未配置</Typography.Text>;
        }
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {r.optionGroups.map((g, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <Tag color="blue" style={{ margin: 0, fontSize: 11 }}>{g.name}</Tag>
                <Typography.Text style={{ fontSize: 11, color: '#64748b' }}>
                  {g.options.slice(0, 3).join('、')}{g.options.length > 3 ? `...${g.options.length}项` : ''}
                </Typography.Text>
              </div>
            ))}
          </div>
        );
      },
    },
    {
      title: '文图理解生成视频提示词', dataIndex: 'skills', ellipsis: true,
      render: (v: string) => {
        try {
          const arr = JSON.parse(v);
          if (Array.isArray(arr)) {
            const wtj = arr.find((s: any) => s.key === '文图理解生成视频提示词' || s.key === '文图理解');
            if (wtj) return <Typography.Text ellipsis style={{ fontSize: 12 }}>{wtj.label}</Typography.Text>;
          }
        } catch { /* ignore */ }
        return <span style={{ color: '#bfbfbf' }}>-</span>;
      },
    },
    {
      title: '文图理解生成图片提示词', dataIndex: 'skills', ellipsis: true,
      render: (v: string) => {
        try {
          const arr = JSON.parse(v);
          if (Array.isArray(arr)) {
            const wtj = arr.find((s: any) => s.key === '文图理解生成图片提示词');
            if (wtj) return <Typography.Text ellipsis style={{ fontSize: 12 }}>{wtj.label}</Typography.Text>;
          }
        } catch { /* ignore */ }
        return <span style={{ color: '#bfbfbf' }}>-</span>;
      },
    },
    {
      title: '状态', dataIndex: 'isActive', width: 80,
      render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '停用'}</Tag>,
    },
    {
      title: '操作', key: 'action', width: 150, fixed: 'right' as const,
      render: (_: any, r: IndustryItem) => (
        <Space size={4}>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => openEdit(r)}>编辑</Button>
          <Popconfirm title="确定删除该行业？" onConfirm={() => handleDelete(r.id)}>
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Space>
            <AppstoreOutlined style={{ fontSize: 18, color: '#6366f1' }} />
            <Typography.Text strong style={{ fontSize: 16 }}>行业与技能配置</Typography.Text>
            <Tag color="purple">{industries.length} 个行业</Tag>
          </Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openEdit()} style={{ borderRadius: 8 }}>
            添加行业
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={industries}
          rowKey="id"
          loading={loading}
          pagination={false}
          scroll={{ x: 900 }}
        />
      </Card>

      <Modal
        title={<Space><AppstoreOutlined />{modal.item ? '编辑行业' : '添加行业'}</Space>}
        open={modal.open}
        onOk={handleSave}
        onCancel={() => { setModal({ open: false, item: null }); form.resetFields(); }}
        okText="保存" cancelText="取消" width={640}
        confirmLoading={saving}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <Form.Item name="key" label="行业标识" style={{ flex: 1 }}
              rules={[{ required: true, message: '请输入标识' }]}>
              <Input placeholder="例如：ecommerce" size="large" />
            </Form.Item>
            <Form.Item name="label" label="行业名称" style={{ flex: 1 }}
              rules={[{ required: true, message: '请输入名称' }]}>
              <Input placeholder="例如：电商" size="large" />
            </Form.Item>
          </div>
          <Form.Item name="icon" label="行业图标">
            <IconPicker />
          </Form.Item>
          <Form.Item name="description" label="行业描述">
            <Input.TextArea rows={2} placeholder="行业描述" size="large" />
          </Form.Item>
          <Form.Item name="skills_wentutujie" label="文图理解生成视频提示词" extra="用于LLM优化视频提示词的系统指令，根据行业特点引导AI理解文案与画面的关系">
            <Input.TextArea rows={3} placeholder="请输入文图理解生成视频提示词，例如：&#10;你是一位专业的电商视频文案专家，擅长将产品卖点转化为视觉语言" size="large" />
          </Form.Item>
          <Form.Item name="skills_wentutujie_image" label="文图理解生成图片提示词" extra="用于LLM优化图片提示词的系统指令，根据行业特点引导AI理解文案与画面的关系">
            <Input.TextArea rows={3} placeholder="请输入文图理解生成图片提示词，例如：&#10;你是一位专业的电商图片文案专家，擅长将产品卖点转化为图片生成提示词" size="large" />
          </Form.Item>

          {/* Option Groups */}
          <div style={{ marginBottom: 8 }}>
            <Typography.Text strong style={{ fontSize: 13 }}>行业选项配置</Typography.Text>
            <Typography.Text style={{ fontSize: 12, color: '#94a3b8', marginLeft: 8 }}>
              添加选项组，每组包含名称和多个选项，前台将显示为下拉选择
            </Typography.Text>
          </div>
          <Form.List name="optionGroups">
            {(fields, { add, remove }) => (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} style={{
                    display: 'flex', gap: 8, alignItems: 'flex-start',
                    padding: '10px 12px', borderRadius: 10,
                    background: '#f8f9fc', border: '1px solid #f0f0f5',
                  }}>
                    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
                      <Form.Item {...restField} name={[name, 'name']} label="选项名称" style={{ marginBottom: 0 }}
                        rules={[{ required: true, message: '请输入选项名称' }]}>
                        <Input placeholder="例如：视频风格" size="middle" style={{ borderRadius: 8 }} />
                      </Form.Item>
                      <Form.Item {...restField} name={[name, 'options']} label="选项内容" style={{ marginBottom: 0 }}>
                        <Select
                          mode="tags"
                          size="middle"
                          placeholder="输入选项后回车添加"
                          style={{ borderRadius: 8 }}
                          tokenSeparators={[',', '，', '、']}
                        />
                      </Form.Item>
                    </div>
                    <MinusCircleOutlined
                      onClick={() => remove(name)}
                      style={{ color: '#ef4444', fontSize: 16, marginTop: 34, cursor: 'pointer', flexShrink: 0 }}
                    />
                  </div>
                ))}
                <Button
                  type="dashed" onClick={() => add()} block
                  icon={<PlusOutlined />}
                  style={{ borderRadius: 8, height: 36 }}
                >
                  添加选项组
                </Button>
              </div>
            )}
          </Form.List>

          <div style={{ display: 'flex', gap: 16 }}>
            <Form.Item name="is_active" label="启用状态" valuePropName="checked" initialValue={true} style={{ flex: 1 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="sort_order" label="排序" initialValue={0} style={{ flex: 1 }}>
              <Input type="number" size="large" />
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminIndustries;
