import { useState, useEffect } from 'react';
import { ticketAPI, lotteryAPI } from '../services/api';
import Camera from '../components/Camera';
import TicketForm from '../components/TicketForm';
import TicketList from '../components/TicketList';
import TicketDetail from '../components/TicketDetail';
import RandomPick from '../components/RandomPick';
import ToastContainer, { showToast } from '../components/Toast';

function Dashboard({ user, onLogout }) {
  const [activeTab, setActiveTab] = useState('stats');
  const [stats, setStats] = useState(null);
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [showCamera, setShowCamera] = useState(false);
  const [parsedData, setParsedData] = useState(null);
  const [selectedTicket, setSelectedTicket] = useState(null);
  const [showRandomPick, setShowRandomPick] = useState(false);
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterType, setFilterType] = useState('all');
  const [editingTicket, setEditingTicket] = useState(null);

  const filteredTickets = tickets.filter(t => {
    if (filterStatus !== 'all' && t.status !== filterStatus) return false;
    if (filterType !== 'all' && t.type !== filterType) return false;
    return true;
  });

  const filteredStats = {
    totalCost: filteredTickets.reduce((sum, t) => sum + Number(t.cost || 0), 0),
    totalPrize: filteredTickets.reduce((sum, t) => sum + Number(t.prize || 0), 0),
    totalCount: filteredTickets.length,
    wonCount: filteredTickets.filter(t => t.status === 'won').length,
  };

  const loadData = async () => {
    try {
      const [statsRes, ticketsRes] = await Promise.all([
        ticketAPI.stats(),
        ticketAPI.list()
      ]);
      setStats(statsRes.data);
      setTickets(ticketsRes.data.tickets);
    } catch (err) {
      console.error('加载数据失败:', err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleRefresh = async () => {
    setLoading(true);
    try {
      await lotteryAPI.refresh();
      await loadData();
      showToast('开奖数据已刷新');
    } catch (err) {
      showToast('刷新失败', 'error');
    }
    setLoading(false);
  };

  const handleCameraCapture = (data) => {
    setParsedData(data);
    setShowCamera(false);
    setShowForm(true);
  };

  const handleFormSubmit = async (data) => {
    try {
      if (editingTicket) {
        await ticketAPI.update(editingTicket.id, data);
        showToast('更新成功');
        setEditingTicket(null);
        setSelectedTicket(null);
      } else {
        await ticketAPI.create(data);
        showToast('添加成功');
      }
      setShowForm(false);
      setParsedData(null);
      if (data.issue) {
        await lotteryAPI.refresh();
      }
      await loadData();
    } catch (err) {
      showToast(err.response?.data?.error || '保存失败', 'error');
    }
  };

  const handleDelete = async (id) => {
    try {
      await ticketAPI.delete(id);
      setSelectedTicket(null);
      await loadData();
      showToast('删除成功');
    } catch (err) {
      showToast('删除失败', 'error');
    }
  };

  const handleEdit = (ticket) => {
    const numbers = ticket.numbers ? JSON.parse(ticket.numbers) : [];
    setEditingTicket(ticket);
    setParsedData({
      type: ticket.type,
      numbers,
      multiple: ticket.multiple,
      is_additional: !!ticket.is_additional,
      issue: ticket.issue || '',
    });
    setSelectedTicket(null);
    setShowForm(true);
  };

  const handlePageRefresh = () => {
    window.location.reload();
  };

  // 详情页
  if (selectedTicket) {
    return (
      <>
        <ToastContainer />
        <TicketDetail
          ticket={selectedTicket}
          onBack={() => setSelectedTicket(null)}
          onDelete={handleDelete}
          onEdit={handleEdit}
        />
      </>
    );
  }

  return (
    <div className="app-container">
      <ToastContainer />
      <nav className="navbar">
        <h1>🎰 彩票记录</h1>
      </nav>

      <div className="container" style={{paddingBottom: '70px'}}>
        {activeTab === 'stats' && (
          <>
            {/* 统计卡片 */}
            {stats && (
              <div className="stats-grid-4">
                <div className="stat-card-mini expense">
                  <h3>总支出</h3>
                  <div className="value">{stats.totalCost.toFixed(2)}</div>
                </div>
                <div className="stat-card-mini income">
                  <h3>总收益</h3>
                  <div className="value">{stats.totalPrize.toFixed(2)}</div>
                </div>
                <div className="stat-card-mini net">
                  <h3>净收入</h3>
                  <div className="value">{stats.netIncome.toFixed(2)}</div>
                </div>
              </div>
            )}

            {/* 操作按钮 */}
            <div style={{display: 'flex', gap: '8px', marginBottom: '8px'}}>
              <button className="btn btn-secondary action-btn" onClick={() => { setParsedData(null); setEditingTicket(null); setShowForm(true); }}>
                ✏️ 手动添加
              </button>
              <button className="btn btn-secondary action-btn" onClick={() => setShowRandomPick(true)}>
                🎲 机选号码
              </button>
              <button className="btn btn-secondary action-btn" onClick={handleRefresh} disabled={loading}>
                🔄 刷新开奖
              </button>
            </div>
            <div style={{display: 'flex', gap: '8px', marginBottom: '20px'}}>
              <button className="btn btn-primary action-btn" onClick={() => setShowCamera(true)}>
                📷 拍照识别
              </button>
            </div>

            {/* 未开奖彩票列表 */}
            {!loading && tickets.filter(t => t.status === 'pending').length > 0 && (
              <TicketList tickets={tickets.filter(t => t.status === 'pending')} onSelect={setSelectedTicket} title="未开奖彩票" />
            )}
          </>
        )}

        {activeTab === 'records' && (
          <>
            {/* 筛选条件 */}
            <div className="filter-section">
              <div className="filter-group">
                <span className="filter-label">状态</span>
                <div className="filter-tags">
                  {[['all','全部'],['pending','未开奖'],['lost','未中奖'],['won','已中奖']].map(([val, label]) => (
                    <button key={val} className={`filter-tag ${filterStatus === val ? 'active' : ''}`} onClick={() => setFilterStatus(val)}>{label}</button>
                  ))}
                </div>
              </div>
              <div className="filter-group">
                <span className="filter-label">类型</span>
                <div className="filter-tags">
                  {[['all','全部'],['welfare','福利彩票'],['sports','体育彩票']].map(([val, label]) => (
                    <button key={val} className={`filter-tag ${filterType === val ? 'active' : ''}`} onClick={() => setFilterType(val)}>{label}</button>
                  ))}
                </div>
              </div>
            </div>

            {/* 筛选结果统计 */}
            <div className="stats-grid-4">
              <div className="stat-card-mini expense">
                <h3>总支出</h3>
                <div className="value">{filteredStats.totalCost.toFixed(2)}</div>
              </div>
              <div className="stat-card-mini income">
                <h3>总收入</h3>
                <div className="value">{filteredStats.totalPrize.toFixed(2)}</div>
              </div>
              <div className="stat-card-mini count">
                <h3>彩票总数</h3>
                <div className="value">{filteredStats.totalCount}</div>
              </div>
              <div className="stat-card-mini net">
                <h3>中奖数</h3>
                <div className="value">{filteredStats.wonCount}</div>
              </div>
            </div>

            {/* 彩票列表 */}
            {loading ? (
              <div className="loading"><div className="spinner"></div>加载中...</div>
            ) : (
              <TicketList tickets={filteredTickets} onSelect={setSelectedTicket} />
            )}
          </>
        )}

        {activeTab === 'mine' && (
          <div className="mine-page">
            <div className="user-info-card">
              <div className="user-avatar">
                {user.username.charAt(0).toUpperCase()}
              </div>
              <div className="user-name">{user.username}</div>
            </div>

            <div className="mine-actions">
              <button className="mine-btn" onClick={handlePageRefresh}>
                <span className="mine-btn-icon">🔄</span>
                <span>刷新页面</span>
              </button>
              <button className="mine-btn logout" onClick={onLogout}>
                <span className="mine-btn-icon">🚪</span>
                <span>退出登录</span>
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 拍照组件 */}
      {showCamera && (
        <Camera
          onCapture={handleCameraCapture}
          onClose={() => setShowCamera(false)}
        />
      )}

      {/* 添加/编辑表单 */}
      {showForm && (
        <TicketForm
          initialData={parsedData}
          editMode={!!editingTicket}
          onSubmit={handleFormSubmit}
          onCancel={() => { setShowForm(false); setParsedData(null); setEditingTicket(null); }}
        />
      )}

      {/* 机选 */}
      {showRandomPick && (
        <RandomPick
          onSubmit={async (data) => {
            try {
              await ticketAPI.create(data);
              setShowRandomPick(false);
              await loadData();
              showToast('保存成功');
            } catch (err) {
              showToast(err.response?.data?.error || '保存失败', 'error');
            }
          }}
          onClose={() => setShowRandomPick(false)}
        />
      )}

      {/* 底部导航 */}
      <div className="bottom-nav">
        <button
          className={`nav-item ${activeTab === 'stats' ? 'active' : ''}`}
          onClick={() => setActiveTab('stats')}
        >
          <span className="nav-icon">📊</span>
          <span className="nav-label">统计</span>
        </button>
        <button
          className={`nav-item ${activeTab === 'records' ? 'active' : ''}`}
          onClick={() => setActiveTab('records')}
        >
          <span className="nav-icon">📋</span>
          <span className="nav-label">记录</span>
        </button>
        <button
          className={`nav-item ${activeTab === 'mine' ? 'active' : ''}`}
          onClick={() => setActiveTab('mine')}
        >
          <span className="nav-icon">👤</span>
          <span className="nav-label">我的</span>
        </button>
      </div>
    </div>
  );
}

export default Dashboard;
