import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Model, ModelDynamic, ModelDynamicStats } from '../types/model';
import { modelService } from '../services/modelService';
import { modelDynamicService } from '../services/modelDynamicService';
import ModelDynamicHeader from '../components/ModelDynamicHeader';
import ModelDynamicList from '../components/ModelDynamicList';
import CreateDynamicModal from '../components/CreateDynamicModal';
import {
  ExclamationTriangleIcon
} from '@heroicons/react/24/outline';

const ModelDynamics: React.FC = () => {
  const { modelId } = useParams<{ modelId: string }>();
  const [model, setModel] = useState<Model | null>(null);
  const [dynamics, setDynamics] = useState<ModelDynamic[]>([]);
  const [stats, setStats] = useState<ModelDynamicStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);

  useEffect(() => {
    if (modelId) {
      loadModelData();
      loadDynamics();
      loadStats();
    }
  }, [modelId]);

  const loadModelData = async () => {
    if (!modelId) return;

    try {
      const modelData = await modelService.getModelById(modelId);
      setModel(modelData);
    } catch (err) {
      console.error('加载模特信息失败:', err);
      setError('加载模特信息失败');
    }
  };

  const loadDynamics = async () => {
    if (!modelId) return;

    try {
      // 使用模拟数据进行开发测试
      const dynamicsList = modelDynamicService.getMockDynamics(modelId);
      setDynamics(dynamicsList);

      // TODO: 后续替换为真实API调用
      // const dynamicsList = await modelDynamicService.getDynamicsByModelId(modelId);
      // setDynamics(dynamicsList);
    } catch (err) {
      console.error('加载动态列表失败:', err);
    }
  };

  const loadStats = async () => {
    if (!modelId) return;

    try {
      // 使用模拟数据进行开发测试
      const statsData = modelDynamicService.getMockStats(modelId);
      setStats(statsData);

      // TODO: 后续替换为真实API调用
      // const statsData = await modelDynamicService.getStatsByModelId(modelId);
      // setStats(statsData);
    } catch (err) {
      console.error('加载统计数据失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateDynamic = async (dynamicData: any) => {
    try {
      // TODO: 实现创建动态API
      // await modelDynamicService.createDynamic(dynamicData);
      console.log('创建动态数据:', dynamicData);
      setShowCreateModal(false);
      await loadDynamics();
      await loadStats();
    } catch (err) {
      console.error('创建动态失败:', err);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6 animate-fade-in">
        {/* 头部骨架 */}
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="flex items-center space-x-4">
            <div className="h-20 w-20 bg-gray-200 rounded-full loading-shimmer" />
            <div className="space-y-2 flex-1">
              <div className="h-6 bg-gray-200 rounded w-32 loading-shimmer" />
              <div className="h-4 bg-gray-200 rounded w-24 loading-shimmer" />
              <div className="h-4 bg-gray-200 rounded w-48 loading-shimmer" />
            </div>
          </div>
        </div>

        {/* 动态列表骨架 */}
        <div className="space-y-4">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="bg-white rounded-xl border border-gray-200 p-6 animate-pulse">
              <div className="space-y-4">
                <div className="h-4 bg-gray-300 rounded w-3/4"></div>
                <div className="h-32 bg-gray-300 rounded"></div>
                <div className="grid grid-cols-3 gap-2">
                  {[...Array(6)].map((_, j) => (
                    <div key={j} className="h-20 bg-gray-300 rounded"></div>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error || !model) {
    return (
      <div className="text-center py-16 animate-fade-in">
        <div className="max-w-md mx-auto">
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <ExclamationTriangleIcon className="h-8 w-8 text-red-500" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
          <p className="text-gray-600 mb-6">{error || '模特信息不存在'}</p>
          <button
            onClick={() => window.history.back()}
            className="px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl hover:from-blue-600 hover:to-blue-700 transition-all duration-200 shadow-sm hover:shadow-md font-medium"
          >
            返回
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* 模特头部信息 */}
      <ModelDynamicHeader
        model={model}
        stats={stats}
        onCreateDynamic={() => setShowCreateModal(true)}
      />

      {/* 动态列表 */}
      <ModelDynamicList
        dynamics={dynamics}
        onRefresh={loadDynamics}
        loading={loading}
        error={error}
      />

      {/* 创建动态模态框 */}
      {showCreateModal && model && (
        <CreateDynamicModal
          model={model}
          onSubmit={handleCreateDynamic}
          onCancel={() => setShowCreateModal(false)}
        />
      )}
    </div>
  );
};

export default ModelDynamics;
