import React, { useEffect, useState } from 'react';
import {
  Button,
  Empty,
  Input,
  message,
  Modal,
  Pagination,
  Select,
  Space,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import {
  PlayCircleOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  LoadingOutlined,
  CopyOutlined,
  FilterOutlined,
  CloseCircleOutlined,
  EditOutlined,
  CaretRightOutlined,
  CaretDownOutlined,
  VideoCameraOutlined,
  DownloadOutlined,
  RocketOutlined,
  PictureOutlined,
} from '@ant-design/icons';
import { useAppStore } from '../store/useAppStore';
import type { GenerationStatus, AspectRatio, Resolution } from '../types';
import { formatDate } from '../utils/formatDate';

const statusConfig: Record<GenerationStatus, { color: string; text: string; icon: React.ReactNode }> = {
  optimizing: { color: 'processing', text: '优化中', icon: <LoadingOutlined spin /> },
  prompt_optimized: { color: 'processing', text: '待生成', icon: <ClockCircleOutlined /> },
  generating: { color: 'warning', text: '生成中', icon: <LoadingOutlined spin /> },
  completed: { color: 'success', text: '已完成', icon: <CheckCircleOutlined /> },
  failed: { color: 'error', text: '失败', icon: <CloseCircleOutlined /> },
};

const RecordsPage: React.FC = () => {
  const { records, projects, fetchRecords, fetchProjects, generateVideo } = useAppStore();
  const recordItems = records.items;
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [generating, setGenerating] = useState<Record<string, boolean>>({});
  const [filterProject, setFilterProject] = useState<string | undefined>(undefined);
  const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
  const [editablePrompts, setEditablePrompts] = useState<Record<string, string>>({});
  const [editingRecordId, setEditingRecordId] = useState<string | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  // Generate modal for param selection
  const [genModal, setGenModal] = useState<{ recordId: string; projectName: string; ratio: AspectRatio; resolution: Resolution } | null>(null);

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

  useEffect(() => {
    fetchRecords({
      projectId: filterProject,
      status: filterStatus,
      page: currentPage,
      pageSize,
    });
  }, [fetchRecords, filterProject, filterStatus, currentPage, pageSize]);

  const handleGenerate = async () => {
    if (!genModal) return;
    const { recordId, projectName, ratio, resolution } = genModal;
    setGenerating((p) => ({ ...p, [recordId]: true }));
    setGenModal(null);
    message.loading({ content: `「${projectName}」正在生成视频...`, duration: 0, key: recordId });
    try {
      await generateVideo(recordId, { aspectRatio: ratio, resolution });
      message.success({ content: `「${projectName}」视频生成成功！`, key: recordId, duration: 3 });
    } catch {
      message.error({ content: `「${projectName}」视频生成失败`, key: recordId, duration: 3 });
    } finally {
      setGenerating((p) => ({ ...p, [recordId]: false }));
    }
  };

  const openGenModal = (record: any) => {
    const type: any = record.genType || 'image';

    // 如果是图片类型，直接生成，不需要弹窗
    if (type === 'image') {
      setGenerating((p) => ({ ...p, [record.id]: true }));
      message.loading({ content: `「${record.projectName}」正在生成图片...`, duration: 0, key: record.id });
      generateVideo(record.id, {}).then(() => {
        message.success({ content: `「${record.projectName}」图片生成成功！`, key: record.id, duration: 3 });
      }).catch(() => {
        message.error({ content: `「${record.projectName}」图片生成失败`, key: record.id, duration: 3 });
      }).finally(() => {
        setGenerating((p) => ({ ...p, [record.id]: false }));
      });
      return;
    }

    // 如果是视频类型，显示参数选择弹窗
    setGenModal({
      recordId: record.id,
      projectName: record.projectName,
      ratio: (record.aspectRatio as AspectRatio) || '16:9',
      resolution: (record.resolution as Resolution) || '720p',
    });
  };

  const filtered = recordItems;

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <Typography.Text style={{ fontSize: 14, color: '#94a3b8' }}>
          查看所有视频生成记录，点击记录查看完整内容和视频
        </Typography.Text>
      </div>

      {/* Filters */}
      <div className="record-filter-bar animate-fadeInUp" style={{
        display: 'flex', gap: 12, marginBottom: 20,
        padding: '14px 20px', borderRadius: 14,
        background: '#fff', border: '1px solid #f0f0f5',
      }}>
        <Space>
          <FilterOutlined style={{ color: '#94a3b8' }} />
          <Select placeholder="全部项目" allowClear style={{ width: 200 }}
            onChange={(v) => { setFilterProject(v); setCurrentPage(1); }}>
            {projects.map((p) => <Select.Option key={p.id} value={p.id}>{p.name}</Select.Option>)}
          </Select>
          <Select placeholder="全部状态" allowClear style={{ width: 140 }}
            onChange={(v) => { setFilterStatus(v); setCurrentPage(1); }}>
            <Select.Option value="prompt_optimized">待生成</Select.Option>
            <Select.Option value="generating">生成中</Select.Option>
            <Select.Option value="completed">已完成</Select.Option>
            <Select.Option value="failed">失败</Select.Option>
          </Select>
        </Space>
        <Typography.Text style={{ marginLeft: 'auto', lineHeight: '32px', color: '#94a3b8', fontSize: 13 }}>
          共 {records.total} 条记录
        </Typography.Text>
      </div>

      {filtered.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无生成记录" style={{ padding: 60 }} />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }} className="stagger-children">
          {filtered.map((record, i) => {
            const isEditing = editingRecordId === record.id;
            const prompt = editablePrompts[record.id] ?? record.optimizedPrompt;
            const isGenerating = generating[record.id];
            const isExpanded = expandedId === record.id;
            const type: any = record.genType || 'image';



            return (
              <div key={record.id} className="animate-slideInCard" style={{ animationDelay: `${i * 0.04}s` }}>
                {/* Record summary row */}
                <div
                  className="record-item"
                  onClick={() => setExpandedId(isExpanded ? null : record.id)}
                  style={{
                    padding: '14px 20px', borderRadius: isExpanded ? '14px 14px 0 0' : 14,
                    background: '#fff', border: '1px solid #f0f0f5',
                    cursor: 'pointer', transition: 'all 0.2s',
                    display: 'flex', alignItems: 'center', gap: 12,
                  }}
                >
                  {/* <div style={{ width: 28, height: 28, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, }}>
                        {type === 'image' ? <span style={{ color: '#d97706', fontSize: 12 }} >图片</span> : <span style={{ color: '#2563eb', fontSize: 12 }} >视频</span>}
                      </div> */}
                  <div style={{ width: 28, height: 28, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, background: type === 'image' ? '#fef3c7' : '#dbeafe' }}>
                    {type === 'image' ? <PictureOutlined style={{ color: '#d97706', fontSize: 12 }} /> : <VideoCameraOutlined style={{ color: '#2563eb', fontSize: 12 }} />}
                  </div>
                  {/* Expand icon */}
                  {isExpanded
                    ? <CaretDownOutlined style={{ color: '#6366f1', fontSize: 12, flexShrink: 0 }} />
                    : <CaretRightOutlined style={{ color: '#cbd5e1', fontSize: 12, flexShrink: 0 }} />}

                  {/* Status */}
                  <Tag color={statusConfig[record.status].color} icon={statusConfig[record.status].icon} style={{ margin: 0 }}>
                    {statusConfig[record.status].text}
                  </Tag>

                  {/* Project */}
                  <Tag style={{ background: '#f0f0ff', border: 'none', color: '#6366f1', margin: 0 }}>
                    {record.projectName}
                  </Tag>

                  {/* Prompt preview */}
                  <Typography.Text style={{
                    flex: 1, fontSize: 13, color: '#475569',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>
                    {prompt}
                  </Typography.Text>

                  {/* Meta */}
                  {type === 'image' ? <span className="mobile-meta" translate="no" style={{ fontSize: 12, color: '#94a3b8', flexShrink: 0 }}>
                    {record.duration ? `${record.imageSize}` : '-'} · {record.imageProportion || '-'} · {record.imagePx || '-'} · <span className="date-display" translate="no">{formatDate(record.createdAt)}</span>
                  </span> : <span className="mobile-meta" translate="no" style={{ fontSize: 12, color: '#94a3b8', flexShrink: 0 }}>
                    {record.duration ? `${record.duration}秒` : '-'} · {record.aspectRatio || '-'} · {record.resolution || '-'} · <span className="date-display" translate="no">{formatDate(record.createdAt)}</span>
                  </span>}

                  {/* Quick actions */}
                  <div className="record-actions" onClick={(e) => e.stopPropagation()}>
                    <Space>
                      {record.status === 'prompt_optimized' && (
                        <Button type="primary" size="small" icon={<PlayCircleOutlined />}
                          loading={isGenerating}
                          onClick={() => openGenModal(record)}
                          style={{
                            borderRadius: 8,
                            background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                            border: 'none',
                          }}>
                          生成
                        </Button>
                      )}
                      {record.status === 'generating' && (
                        <Tag color="processing" icon={<LoadingOutlined spin />} style={{ padding: '4px 12px', fontSize: 12 }}>
                          生成中...
                        </Tag>
                      )}
                      {record.status === 'failed' && (
                        <Button type="primary" danger size="small" icon={<PlayCircleOutlined />}
                          loading={isGenerating}
                          onClick={() => openGenModal(record)}
                          style={{ borderRadius: 8 }}>
                          重试
                        </Button>
                      )}
                    </Space>
                  </div>
                </div>

                {/* Expanded detail panel */}
                {isExpanded && (
                  <div style={{
                    background: '#fff',
                    border: '1px solid #f0f0f5',
                    borderTop: 'none',
                    borderRadius: '0 0 14px 14px',
                    padding: '20px 24px',
                    animation: 'fadeInUp 0.25s ease both',
                  }}>
                    <div className="gen-detail-row" style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
                      {/* Left: full info */}
                      <div style={{ flex: '1 1 50%', minWidth: 280 }}>
                        {/* Original prompt */}
                        <div style={{ marginBottom: 16 }}>
                          <Typography.Text style={{ fontSize: 12, color: '#94a3b8', display: 'block', marginBottom: 6 }}>
                            原始提示词
                          </Typography.Text>
                          <div style={{
                            padding: 12, borderRadius: 10,
                            background: '#f8f9fc', border: '1px solid #f0f0f5',
                          }}>
                            <Typography.Text style={{ fontSize: 13, color: '#64748b', lineHeight: 1.7 }}>
                              {record.originalPrompt}
                            </Typography.Text>
                          </div>
                        </div>

                        {/* Optimized prompt (editable) */}
                        <div style={{ marginBottom: 16 }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                            <Typography.Text style={{ fontSize: 12, color: '#94a3b8' }}>
                              优化后的提示词 {record.status === 'prompt_optimized' && <span style={{ color: '#6366f1' }}>（可编辑）</span>}
                            </Typography.Text>
                            {!isEditing && (
                              <Space size={4}>
                                <Tooltip title="复制">
                                  <Button type="text" size="small" icon={<CopyOutlined />}
                                    onClick={() => { navigator.clipboard.writeText(prompt); message.success('已复制'); }}
                                    style={{ color: '#94a3b8' }} />
                                </Tooltip>
                                {record.status === 'prompt_optimized' && (
                                  <Tooltip title="编辑">
                                    <Button type="text" size="small" icon={<EditOutlined />}
                                      onClick={() => {
                                        setEditingRecordId(record.id);
                                        setEditablePrompts((p) => ({ ...p, [record.id]: p[record.id] ?? record.optimizedPrompt }));
                                      }}
                                      style={{ color: '#6366f1' }} />
                                  </Tooltip>
                                )}
                              </Space>
                            )}
                          </div>
                          {isEditing ? (
                            <div>
                              <Input.TextArea value={prompt}
                                onChange={(e) => setEditablePrompts((p) => ({ ...p, [record.id]: e.target.value }))}
                                rows={4}
                                style={{
                                  borderRadius: 10, fontSize: 13, lineHeight: 1.7,
                                  border: '1px solid rgba(99,102,241,0.25)',
                                  background: 'rgba(99,102,241,0.02)',
                                }} />
                              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 8 }}>
                                <Button size="small" onClick={() => setEditingRecordId(null)}>取消</Button>
                                <Button size="small" type="primary" onClick={() => {
                                  setEditablePrompts((p) => ({ ...p, [record.id]: prompt }));
                                  setEditingRecordId(null);
                                  message.success('提示词已更新');
                                }} style={{
                                  borderRadius: 6,
                                  background: 'linear-gradient(135deg, #6366f1, #8b5cf6)', border: 'none',
                                }}>保存</Button>
                              </div>
                            </div>
                          ) : (
                            <div style={{
                              padding: 12, borderRadius: 10,
                              background: 'rgba(99,102,241,0.02)', border: '1px solid rgba(99,102,241,0.1)',
                            }}>
                              <Typography.Text style={{ fontSize: 13, color: '#1a1a2e', lineHeight: 1.7 }}>
                                {prompt}
                              </Typography.Text>
                            </div>
                          )}
                        </div>

                        {/* Params */}
                        <div style={{
                          display: 'flex', gap: 16, padding: '12px 16px',
                          borderRadius: 10, background: '#f8f9fc',
                        }}>
                          {type === 'image' ? [
                            { label: '分辨率', value: record.imageSize ? `${record.imageSize} ` : '-' },
                            { label: '画面比例', value: record.imageProportion ? `${record.imageProportion} ` : '-' },
                            { label: '画面尺寸', value: record.imageProportion ? `${record.imageProportion} ` : '-' },
                            { label: '消耗积分', value: record.creditsCost ? `${record.creditsCost} ` : '-', highlight: !!record.creditsCost },
                          ].map((item, j) => (
                            <div key={j} style={{ flex: 1 }}>
                              <Typography.Text style={{ fontSize: 11, color: '#94a3b8', display: 'block' }}>{item.label}</Typography.Text>
                              <Typography.Text strong style={{ fontSize: 14, color: item.highlight ? '#6366f1' : '#1a1a2e' }}>{item.value}</Typography.Text>
                            </div>
                          )) : [
                            { label: '时长', value: record.duration ? `${record.duration} 秒` : '-' },
                            { label: '画面比例', value: record.aspectRatio || (record.status === 'prompt_optimized' ? '待选择' : '-') },
                            { label: '分辨率', value: record.resolution || (record.status === 'prompt_optimized' ? '待选择' : '-') },
                            { label: '消耗积分', value: record.creditsCost ? `${record.creditsCost}` : '-', highlight: !!record.creditsCost },
                          ].map((item, j) => (
                            <div key={j} style={{ flex: 1 }}>
                              <Typography.Text style={{ fontSize: 11, color: '#94a3b8', display: 'block' }}>{item.label}</Typography.Text>
                              <Typography.Text strong style={{ fontSize: 14, color: item.highlight ? '#6366f1' : '#1a1a2e' }}>{item.value}</Typography.Text>
                            </div>
                          ))}
                        </div>

                        {/* Generate button in detail */}
                        {record.status === 'prompt_optimized' && (
                          <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
                            <Button type="primary" size="large" icon={<RocketOutlined />}
                              loading={isGenerating}
                              onClick={() => openGenModal(record)}
                              style={{
                                borderRadius: 12, fontWeight: 600, height: 44,
                                background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                                border: 'none', boxShadow: '0 8px 24px rgba(99,102,241,0.3)',
                              }}>
                              {type === 'video' ? '选择参数生成视频' : '生成图片'}
                            </Button>
                          </div>
                        )}

                        {/* Failed retry */}
                        {record.status === 'failed' && (
                          <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
                            <Button type="primary" danger size="large" icon={<PlayCircleOutlined />}
                              loading={isGenerating}
                              onClick={() => openGenModal(record)}
                              style={{ borderRadius: 12, fontWeight: 600, height: 44 }}>
                              重新生成{type === 'video' ? '视频' : '图片'}
                            </Button>
                          </div>
                        )}
                      </div>

                      {/* Right: video preview */}
                      <div style={{ flex: '1 1 40%', minWidth: 240 }}>
                        {record.status === 'generating' ? (
                          <div style={{
                            height: '100%', minHeight: 200, borderRadius: 14,
                            background: 'linear-gradient(135deg, rgba(99,102,241,0.04), rgba(139,92,246,0.04))',
                            border: '1px dashed rgba(99,102,241,0.2)',
                            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12,
                          }}>
                            <LoadingOutlined style={{ color: '#6366f1', fontSize: 32 }} spin />
                            <Typography.Text style={{ color: '#94a3b8', fontSize: 14 }}>{type === 'video' ? '视频' : '图片'}生成中...</Typography.Text>
                            <Typography.Text style={{ color: '#cbd5e1', fontSize: 12 }}>请耐心等待，生成完成后将自动展示</Typography.Text>
                          </div>
                        ) : record.status === 'completed' && (record.videoUrl || record.imageUrl) ? (
                          <div style={{ borderRadius: 14, overflow: 'hidden', border: '1px solid #f0f0f5', position: 'relative' }}>
                            <div style={{ position: 'absolute', top: 10, right: 10, zIndex: 10 }}>
                              <Tooltip title={`下载${type === 'video' ? '视频' : '图片'}`}>
                                <Button size="small" icon={<DownloadOutlined />}
                                  onClick={() => { const a = document.createElement('a'); a.href = `${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}${type === 'video' ? record.videoUrl : record.imageUrl}&download=1`; a.download = `${record.projectName}${type === 'video' ? '.mp4' : '.png'}`; a.click(); }}
                                  style={{ background: 'rgba(0,0,0,0.5)', border: 'none', color: '#fff', backdropFilter: 'blur(4px)', borderRadius: 8 }}>
                                  下载
                                </Button>
                              </Tooltip>
                            </div>
                            <div style={{ minHeight: 280, overflow: 'hidden' }}>
                              {type === 'video' ? (
                                <video
                                  src={`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}${record.videoUrl}`}
                                  controls
                                  preload="metadata"
                                  style={{ width: '100%', height: '400px', display: 'block' }}
                                />
                              ) : (
                                <img
                                  src={`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}${record.imageUrl}`}
                                  alt={record.projectName}
                                  style={{ width: '100%', maxHeight: '400px', objectFit: 'contain', display: 'block' }}
                                />  
                              )}
                            </div>
                            <div style={{
                              padding: '10px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                              background: '#fafbff',
                            }}>
                              <Space>
                                {type === 'video' ? <VideoCameraOutlined style={{ color: '#6366f1' }} /> : <PictureOutlined style={{ color: '#6366f1' }} />}
                                <Typography.Text style={{ fontSize: 13, color: '#475569' }}>
                                  {record.projectName}
                                </Typography.Text>
                              </Space>
                              {record.generatedAt && (
                                <span className="date-display" translate="no" style={{ fontSize: 12, color: '#94a3b8' }}>
                                  生成于 {formatDate(record.generatedAt)}
                                </span>
                              )}
                            </div>
                          </div>
                        ) : record.status === 'failed' ? (
                          <div style={{
                            height: '100%', minHeight: 200, borderRadius: 14,
                            background: 'rgba(239,68,68,0.03)',
                            border: '1px dashed rgba(239,68,68,0.2)',
                            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12,
                          }}>
                            <CloseCircleOutlined style={{ color: '#ef4444', fontSize: 32 }} />
                            <Typography.Text style={{ color: '#ef4444', fontSize: 14 }}>{type === 'video' ? '视频' : '图片'}生成失败</Typography.Text>
                            <Typography.Text style={{ color: '#94a3b8', fontSize: 12 }}>请在左侧点击重新生成</Typography.Text>
                          </div>
                        ) : (
                          <div style={{
                            height: '100%', minHeight: 200, borderRadius: 14,
                            background: '#f8f9fc', border: '1px dashed #e2e8f0',
                            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12,
                          }}>
                            <ClockCircleOutlined style={{ color: '#94a3b8', fontSize: 32 }} />
                            <Typography.Text style={{ color: '#94a3b8', fontSize: 14 }}>待生成{type === 'video' ? '视频' : '图片'}</Typography.Text>
                            <Typography.Text style={{ color: '#cbd5e1', fontSize: 12 }}>点击左侧生成按钮开始生成</Typography.Text>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {records.total > 0 && (
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 18 }}>
          <Pagination
            current={records.page || currentPage}
            pageSize={records.pageSize || pageSize}
            total={records.total}
            showSizeChanger
            showTotal={(total) => `共 ${total} 条记录`}
            onChange={(page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }}
          />
        </div>
      )}

      {/* Generate modal */}
      <Modal
        title={<Space><RocketOutlined />生成视频</Space>}
        open={!!genModal}
        onCancel={() => setGenModal(null)}
        onOk={handleGenerate}
        okText="提交生成"
        cancelText="取消"
        width={420}
      >
        {genModal && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 16 }}>
            {(() => {
              const rec = recordItems.find(r => r.id === genModal.recordId);
              return (
                <>
                  <div style={{ padding: 12, borderRadius: 10, background: '#f8f9fc' }}>
                    <Typography.Text style={{ fontSize: 11, color: '#94a3b8', display: 'block' }}>时长</Typography.Text>
                    <Typography.Text strong>{rec?.duration || 5}秒</Typography.Text>
                  </div>
                  <div>
                    <Typography.Text style={{ fontSize: 12, color: '#64748b', display: 'block', marginBottom: 6 }}>画面比例</Typography.Text>
                    <Select value={genModal.ratio} onChange={(v) => setGenModal(prev => prev ? { ...prev, ratio: v } : null)}
                      style={{ width: '100%' }}
                      options={['16:9', '4:3', '1:1', '3:4', '9:16', '21:9'].map(r => ({ value: r, label: r }))}
                    />
                  </div>
                  <div>
                    <Typography.Text style={{ fontSize: 12, color: '#64748b', display: 'block', marginBottom: 6 }}>分辨率</Typography.Text>
                    <Select value={genModal.resolution} onChange={(v) => setGenModal(prev => prev ? { ...prev, resolution: v } : null)}
                      style={{ width: '100%' }}
                      options={['480p', '720p', '1080p'].map(r => ({ value: r, label: r }))}
                    />
                  </div>
                </>
              );
            })()}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default RecordsPage;
