import React, { useEffect, useState } from 'react';
import {
  Button, Empty, Form, Input, message, Modal,
  Popconfirm, Select, Space, Tag, Typography,
} from 'antd';
import {
  PlusOutlined, DeleteOutlined, PlayCircleOutlined,
  FolderOpenOutlined, CalendarOutlined, AppstoreOutlined, RightOutlined,
  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, 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 { useNavigate } from 'react-router-dom';
import { useAppStore } from '../store/useAppStore';
import { getIndustries } from '../api';
import type { IndustryConfig } from '../types';
import { formatDate } from '../utils/formatDate';

const defaultColors = ['#f97316', '#3b82f6', '#8b5cf6', '#10b981', '#eab308', '#6366f1', '#ef4444', '#06b6d4', '#64748b', '#78716c'];

const iconMap: Record<string, React.ReactNode> = {
  ShoppingCartOutlined: <ShoppingCartOutlined />,
  BookOutlined: <BookOutlined />,
  HomeOutlined: <HomeOutlined />,
  FireOutlined: <FireOutlined />,
  RocketOutlined: <RocketOutlined />,
  SkinOutlined: <SkinOutlined />,
  CompassOutlined: <CompassOutlined />,
  HeartOutlined: <HeartOutlined />,
  CarOutlined: <CarOutlined />,
  CameraOutlined: <CameraOutlined />,
  CloudOutlined: <CloudOutlined />,
  StarOutlined: <StarOutlined />,
  TrophyOutlined: <TrophyOutlined />,
  ThunderboltOutlined: <ThunderboltOutlined />,
  BulbOutlined: <BulbOutlined />,
  CoffeeOutlined: <CoffeeOutlined />,
  CrownOutlined: <CrownOutlined />,
  DashboardOutlined: <DashboardOutlined />,
  FlagOutlined: <FlagOutlined />,
  GlobalOutlined: <GlobalOutlined />,
  GiftOutlined: <GiftOutlined />,
  LaptopOutlined: <LaptopOutlined />,
  MobileOutlined: <MobileOutlined />,
  MonitorOutlined: <MonitorOutlined />,
  PayCircleOutlined: <PayCircleOutlined />,
  PictureOutlined: <PictureOutlined />,
  PlayCircleOutlined: <PlayCircleOutlined />,
  SafetyOutlined: <SafetyOutlined />,
  ShoppingOutlined: <ShoppingOutlined />,
  SmileOutlined: <SmileOutlined />,
  SoundOutlined: <SoundOutlined />,
  TagOutlined: <TagOutlined />,
  TeamOutlined: <TeamOutlined />,
  ToolOutlined: <ToolOutlined />,
  TruckOutlined: <TruckOutlined />,
  VideoCameraOutlined: <VideoCameraOutlined />,
  WalletOutlined: <WalletOutlined />,
  BankOutlined: <BankOutlined />,
  BuildOutlined: <BuildOutlined />,
  ExperimentOutlined: <ExperimentOutlined />,
  HighlightOutlined: <HighlightOutlined />,
  IdcardOutlined: <IdcardOutlined />,
  MedicineBoxOutlined: <MedicineBoxOutlined />,
  ReadOutlined: <ReadOutlined />,
  RestOutlined: <RestOutlined />,
  SketchOutlined: <SketchOutlined />,
  SolutionOutlined: <SolutionOutlined />,
};

const ProjectsPage: React.FC = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { projects, fetchProjects, createProject, deleteProject } = useAppStore();
  const [industries, setIndustries] = useState<IndustryConfig[]>([]);

  useEffect(() => { fetchProjects(); getIndustries().then(setIndustries).catch(() => {}); }, []);

  const industryMap = Object.fromEntries(industries.map((ind, i) => [ind.key, { label: ind.label, color: defaultColors[i % defaultColors.length], icon: ind.icon || 'AppstoreOutlined' }]));

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      const project = await createProject(values.name, values.industry);
      message.success('项目创建成功');
      setModalOpen(false); form.resetFields();
      navigate(`/projects/${project.id}/generate`);
    } catch { /* */ }
  };

  return (
    <div>
      {/* Header banner */}
      <div className="animate-fadeInUp" style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginBottom: 24, padding: '22px 24px', borderRadius: 16,
        background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
        position: 'relative', overflow: 'hidden', flexWrap: 'wrap', gap: 12,
      }}>
        <div style={{ position: 'absolute', right: -20, top: -20, width: 200, height: 200, borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }} />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Typography.Title level={3} style={{ margin: '0 0 4px', color: '#fff', fontWeight: 700 }}>我的项目</Typography.Title>
          <Typography.Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: 14 }}>
            共 {projects.length} 个项目 · 按行业分类管理
          </Typography.Text>
        </div>
        <Button icon={<PlusOutlined />} onClick={() => setModalOpen(true)} size="large" style={{
          background: 'rgba(255,255,255,0.15)', border: '1px solid rgba(255,255,255,0.3)',
          color: '#fff', fontWeight: 600, backdropFilter: 'blur(10px)', borderRadius: 10, height: 42,
        }}>新建项目</Button>
      </div>

      {projects.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="还没有项目，创建您的第一个视频项目" style={{ padding: '60px 0' }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalOpen(true)} size="large">创建第一个项目</Button>
        </Empty>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }} className="stagger-children">
          {projects.map((project, i) => (
            <div key={project.id} className="project-card project-item animate-slideInCard" onClick={() => navigate(`/projects/${project.id}/generate`)}
              style={{
                display: 'flex', alignItems: 'center', padding: '18px 22px', borderRadius: 16,
                background: '#fff', border: '1px solid #f0f0f5', cursor: 'pointer',
                animationDelay: `${i * 0.06}s`,
              }}>
              <div style={{
                width: 50, height: 50, borderRadius: 14, flexShrink: 0,
                background: `${industryMap[project.industry]?.color || '#64748b'}12`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 24, marginRight: 16, color: industryMap[project.industry]?.color || '#64748b',
              }}>{iconMap[industryMap[project.industry]?.icon] || <AppstoreOutlined />}</div>

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                  <Typography.Text strong style={{ fontSize: 15, color: '#1a1a2e' }}>{project.name}</Typography.Text>
                  <Tag color={industryMap[project.industry]?.color || '#64748b'} style={{ borderRadius: 6, margin: 0 }}>{industryMap[project.industry]?.label || project.industry}</Tag>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <CalendarOutlined style={{ fontSize: 12, color: '#94a3b8' }} />
                  <span className="date-display" translate="no" style={{ fontSize: 12, color: '#94a3b8' }}>创建于 {formatDate(project.createdAt)}</span>
                </div>
              </div>

              <div className="project-actions" style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 16 }}>
                <Button type="primary" icon={<PlayCircleOutlined />}
                  onClick={(e) => { e.stopPropagation(); navigate(`/projects/${project.id}/generate`); }}
                  style={{
                    background: 'linear-gradient(135deg, #6366f1, #8b5cf6)', border: 'none',
                    borderRadius: 10, fontWeight: 600, height: 36,
                    boxShadow: '0 4px 12px rgba(99,102,241,0.25)',
                  }}>生成</Button>
                <Popconfirm title="确定删除该项目？" description="项目下的生成记录将一并删除"
                  onConfirm={async (e) => { e?.stopPropagation(); await deleteProject(project.id); message.success('项目已删除'); }}
                  onCancel={(e) => e?.stopPropagation()}>
                  <Button danger icon={<DeleteOutlined />} onClick={(e) => e.stopPropagation()}
                    style={{ borderRadius: 10, height: 36, background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.15)', color: '#ef4444' }} />
                </Popconfirm>
                <RightOutlined className="mobile-hide" style={{ color: '#cbd5e1', fontSize: 12 }} />
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal title={<Space><AppstoreOutlined />新建项目</Space>} open={modalOpen} onOk={handleCreate}
        onCancel={() => { setModalOpen(false); form.resetFields(); }}
        okText="创建" cancelText="取消" width={480}>
        <Form form={form} layout="vertical" style={{ marginTop: 20 }}>
          <Form.Item name="name" label="项目名称" rules={[{ required: true, message: '请输入项目名称' }]}>
            <Input placeholder="例如：618电商大促宣传片" prefix={<FolderOpenOutlined />} size="large" />
          </Form.Item>
          <Form.Item name="industry" label="所属行业" rules={[{ required: true, message: '请选择行业' }]}>
            <Select placeholder="选择项目所属行业" size="large">
              {industries.map((ind, i) => (
                <Select.Option key={ind.key} value={ind.key}><Space>{iconMap[ind.icon] || <AppstoreOutlined />} {ind.label}</Space></Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProjectsPage;
