
import React, { useEffect, useState } from 'react';
import { ApiService, DashboardStats } from '../api';
import { TrangThaiHoSo } from '../types';
import { useNavigate } from 'react-router-dom';

const Dashboard: React.FC = () => {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [aiSettings, setAiSettings] = useState<any>({
    provider: 'gemini',
    gemini: { apiKey: '', model: 'gemini-2.0-flash' },
    ollama: { url: 'http://localhost:11434', model: 'llama3.2-vision' },
    anythingLLM: { url: 'http://localhost:3001', apiKey: '', workspace: '' }
  });
  const navigate = useNavigate();

  useEffect(() => {
    ApiService.getDashboardStats()
      .then(setStats)
      .catch(err => {
        console.error('Error loading dashboard stats:', err);
        // Set empty stats on error
        setStats({
          total: 0,
          draft: 0,
          ready: 0,
          archived: 0,
          recentActivity: []
        });
      });

    // Load AI settings
    ApiService.getSettings()
      .then((settings: any) => {
        if (settings.ai) {
          setAiSettings(settings.ai);
        }
      })
      .catch(err => {
        console.error('Error loading AI settings:', err);
      });
  }, []);

  if (!stats) return <div className="flex items-center justify-center py-20"><div className="w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div></div>;

  // Get AI provider description
  const getAiDescription = () => {
    const provider = aiSettings.provider || 'gemini';
    if (provider === 'gemini') {
      const model = aiSettings.gemini?.model || 'gemini-2.0-flash';
      return `Sử dụng công nghệ ${model} mới nhất để tự động trích xuất thông tin từ tệp quét (Scan) chỉ trong vài giây.`;
    } else if (provider === 'ollama') {
      const model = aiSettings.ollama?.model || 'llama3.2-vision';
      return `Sử dụng ${model} chạy nội bộ để tự động trích xuất thông tin từ tệp quét (Scan) chỉ trong vài giây.`;
    } else if (provider === 'anything_llm') {
      return `Sử dụng AnythingLLM Enterprise để tự động trích xuất thông tin từ tệp quét (Scan) chỉ trong vài giây.`;
    }
    return `Sử dụng công nghệ AI để tự động trích xuất thông tin từ tệp quét (Scan) chỉ trong vài giây.`;
  };

  const cards = [
    { label: 'Tổng số hồ sơ', count: stats.total, color: 'bg-blue-500', icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z' },
    { label: 'Đang xử lý (Draft)', count: stats.draft, color: 'bg-orange-500', icon: 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5' },
    { label: 'Sẵn sàng in ấn', count: stats.ready, color: 'bg-green-500', icon: 'M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z' },
    { label: 'Đã lưu trữ', count: stats.archived, color: 'bg-slate-500', icon: 'M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {cards.map(c => (
          <div key={c.label} className="bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl p-6 rounded-[2rem] border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-2xl hover:scale-[1.02] transition-all duration-300 group">
            <div className="flex items-center justify-between mb-4">
               <div className={`w-12 h-12 ${c.color} rounded-2xl flex items-center justify-center text-white shadow-xl group-hover:scale-110 group-hover:rotate-6 transition-all duration-300`}>
                 <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d={c.icon} /></svg>
               </div>
               <span className="text-3xl font-black text-slate-800 dark:text-white tracking-tighter group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">{c.count}</span>
            </div>
            <p className="text-xs font-black text-slate-500 dark:text-slate-400 uppercase tracking-widest">{c.label}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-[2.5rem] border border-gray-200/50 dark:border-slate-700/50 overflow-hidden shadow-lg">
           <div className="p-8 border-b border-gray-50 dark:border-slate-800 flex justify-between items-center bg-gray-50/50 dark:bg-slate-800/30">
              <h3 className="text-lg font-black text-slate-800 dark:text-white uppercase tracking-tighter">Hoạt động xử lý gần đây</h3>
              <button onClick={() => navigate('/ho-so')} className="text-[10px] font-black text-blue-600 uppercase tracking-widest hover:underline">Xem tất cả</button>
           </div>
           <div className="p-8 space-y-4">
              {stats.recentActivity.map(job => (
                <div key={job.id} onClick={() => navigate(`/ho-so/${job.id}`)} className="flex items-center p-5 bg-white/60 dark:bg-slate-800/60 backdrop-blur-sm rounded-2xl border border-gray-200/50 dark:border-slate-700/50 hover:border-blue-500 hover:bg-white/90 dark:hover:bg-slate-800/90 hover:shadow-lg transition-all duration-300 cursor-pointer group">
                   <div className="w-10 h-10 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded-xl flex items-center justify-center mr-4 group-hover:rotate-6 transition-transform font-black">
                      {job.formData.TEN_CONG_TY?.charAt(0) || 'H'}
                   </div>
                   <div className="flex-1 min-w-0">
                      <p className="text-sm font-black text-slate-800 dark:text-slate-200 truncate">{job.formData.TEN_CONG_TY || 'Hồ sơ chưa đặt tên'}</p>
                      <p className="text-[10px] text-slate-400 font-bold uppercase tracking-tighter">{job.templateName} • {new Date(job.ngayCapNhat).toLocaleDateString('vi-VN')}</p>
                   </div>
                   <span className={`ml-4 px-3 py-1 rounded-lg text-[9px] font-black uppercase ${
                     job.trangThai === TrangThaiHoSo.SAN_SANG_IN ? 'bg-green-100 text-green-700' : 'bg-orange-100 text-orange-700'
                   }`}>
                     {job.trangThai.replace(/_/g, ' ')}
                   </span>
                </div>
              ))}
           </div>
        </div>

        <div className="bg-gradient-to-br from-blue-600 to-indigo-700 rounded-[2.5rem] p-10 text-white shadow-2xl shadow-blue-600/20 flex flex-col justify-between">
           <div className="space-y-6">
              <div className="w-16 h-16 bg-white/20 backdrop-blur-md rounded-2xl flex items-center justify-center">
                 <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
              </div>
              <h4 className="text-3xl font-black leading-tight tracking-tighter">Số hóa hồ sơ nhanh hơn với AI.</h4>
              <p className="text-blue-100 text-sm font-medium leading-relaxed">{getAiDescription()}</p>
           </div>
           <button onClick={() => navigate('/ho-so')} className="mt-10 w-full py-4 bg-white text-blue-600 font-black rounded-2xl hover:bg-blue-50 transition-all shadow-xl">BẮT ĐẦU NGAY</button>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
