import { useGameStore } from '@/store';
import { formatMoney, formatPercent, formatNumber, FUNDING_ROUNDS } from '@ai-tycoon/shared';
import type { FundingRoundType } from '@ai-tycoon/shared';
import { TrendingUp, DollarSign, PiggyBank, BarChart3, Rocket, Check, X as XIcon } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, ResponsiveContainer, LineChart, Line, Tooltip } from 'recharts';
import { canRaiseFunding } from '@ai-tycoon/game-engine';
import type { GameState } from '@ai-tycoon/shared';

export function FinancePage() {
  const money = useGameStore((s) => s.economy.money);
  const revenuePerTick = useGameStore((s) => s.economy.revenuePerTick);
  const expensesPerTick = useGameStore((s) => s.economy.expensesPerTick);
  const funding = useGameStore((s) => s.economy.funding);
  const history = useGameStore((s) => s.economy.financialHistory);
  const infrastructure = useGameStore((s) => s.infrastructure);
  const talent = useGameStore((s) => s.talent);
  const raiseFunding = useGameStore((s) => s.raiseFunding);
  const totalRevenue = useGameStore((s) => s.economy.totalRevenue);
  const subscribers = useGameStore((s) => s.market.consumerTiers.totalUsers);
  const reputationScore = useGameStore((s) => s.reputation.score);

  const state = useGameStore.getState();
  const gameStateForFunding: GameState = {
    meta: state.meta, economy: state.economy, infrastructure: state.infrastructure,
    compute: state.compute, research: state.research, models: state.models,
    market: state.market, competitors: state.competitors, talent: state.talent,
    data: state.data, reputation: state.reputation,
    achievements: state.achievements,
  };
  const fundingStatus = canRaiseFunding(gameStateForFunding);

  const netIncome = revenuePerTick - expensesPerTick;
  const burnRate = expensesPerTick > revenuePerTick ? expensesPerTick - revenuePerTick : 0;
  const runway = burnRate > 0 ? money / burnRate : Infinity;

  let infraCosts = 0;
  for (const cluster of infrastructure.clusters) {
    for (const campus of cluster.campuses) {
      for (const dc of campus.dataCenters) {
        infraCosts += dc.energyCostPerTick + dc.maintenanceCostPerTick;
      }
    }
  }
  const talentCosts = talent.totalSalaryPerTick;

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">Finance</h2>

      <div className="grid grid-cols-4 gap-4">
        <FinanceCard icon={DollarSign} label="Cash" value={formatMoney(money)} color="text-green-400" />
        <FinanceCard
          icon={TrendingUp}
          label="Net Income/s"
          value={formatMoney(netIncome)}
          color={netIncome >= 0 ? 'text-green-400' : 'text-red-400'}
        />
        <FinanceCard icon={PiggyBank} label="Valuation" value={formatMoney(funding.valuation)} color="text-purple-400" />
        <FinanceCard
          icon={BarChart3}
          label="Runway"
          value={runway === Infinity ? 'Infinite' : `${Math.floor(runway / 3600)}h`}
          color={runway < 3600 ? 'text-red-400' : 'text-blue-400'}
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
          <h3 className="text-sm font-medium text-surface-400 mb-4">Cash Over Time</h3>
          {history.length > 1 ? (
            <ResponsiveContainer width="100%" height={200}>
              <AreaChart data={history}>
                <defs>
                  <linearGradient id="cashGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#6366f1" stopOpacity={0.3} />
                    <stop offset="100%" stopColor="#6366f1" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <XAxis dataKey="tick" hide />
                <YAxis width={50} tickFormatter={(v: number) => formatMoney(v)} tick={{ fontSize: 10, fill: '#64748b' }} axisLine={false} tickLine={false} />
                <Area type="monotone" dataKey="money" stroke="#6366f1" fill="url(#cashGrad)" />
              </AreaChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[200px] flex items-center justify-center text-surface-500 text-sm">
              Data will appear as time passes
            </div>
          )}
        </div>

        <div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-medium text-surface-400">Revenue vs Expenses</h3>
            <div className="flex items-center gap-4 text-xs">
              <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-success inline-block" />Revenue</span>
              <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-danger inline-block" />Expenses</span>
            </div>
          </div>
          {history.length > 1 ? (
            <ResponsiveContainer width="100%" height={200}>
              <LineChart data={history}>
                <XAxis dataKey="tick" hide />
                <YAxis width={50} tickFormatter={(v: number) => formatMoney(v)} tick={{ fontSize: 10, fill: '#64748b' }} axisLine={false} tickLine={false} />
                <Tooltip
                  contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #334155', borderRadius: '8px' }}
                  formatter={(value: number, name: string) => [formatMoney(value), name === 'revenue' ? 'Revenue' : 'Expenses']}
                />
                <Line type="monotone" dataKey="revenue" stroke="#22c55e" dot={false} strokeWidth={2} />
                <Line type="monotone" dataKey="expenses" stroke="#ef4444" dot={false} strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[200px] flex items-center justify-center text-surface-500 text-sm">
              Data will appear as time passes
            </div>
          )}
        </div>
      </div>

      <div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
        <h3 className="text-sm font-medium text-surface-400 mb-4">Income Statement (per second)</h3>
        <div className="space-y-3">
          <div className="flex justify-between text-sm">
            <span className="text-surface-300">Revenue</span>
            <span className="font-mono text-success">{formatMoney(revenuePerTick)}</span>
          </div>
          <div className="border-t border-surface-700" />
          <div className="flex justify-between text-sm">
            <span className="text-surface-400 pl-4">Infrastructure</span>
            <span className="font-mono text-danger">-{formatMoney(infraCosts)}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-surface-400 pl-4">Talent</span>
            <span className="font-mono text-danger">-{formatMoney(talentCosts)}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-surface-400 pl-4">Total Expenses</span>
            <span className="font-mono text-danger">-{formatMoney(expensesPerTick)}</span>
          </div>
          <div className="border-t border-surface-700" />
          <div className="flex justify-between text-sm font-semibold">
            <span>Net Income</span>
            <span className={`font-mono ${netIncome >= 0 ? 'text-success' : 'text-danger'}`}>
              {formatMoney(netIncome)}
            </span>
          </div>
        </div>
      </div>

      <div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
        <h3 className="text-sm font-medium text-surface-400 mb-3">Funding</h3>
        <div className="flex items-center gap-4 mb-3">
          <div className="text-sm">
            Founder Equity: <span className="font-mono font-semibold">{formatPercent(funding.founderEquity)}</span>
          </div>
          <div className="text-sm">
            Total Raised: <span className="font-mono font-semibold">{formatMoney(funding.totalRaised)}</span>
          </div>
          {funding.isPublic && (
            <span className="text-xs px-2 py-1 rounded-full bg-accent/20 text-accent-light">Public</span>
          )}
        </div>

        {fundingStatus.nextRound && (() => {
          const roundConfig = FUNDING_ROUNDS[fundingStatus.nextRound as FundingRoundType];
          const reqs = roundConfig.requirements;
          const checks = [
            ...(reqs.minRevenue ? [{ label: `Total Revenue: ${formatMoney(totalRevenue)} / ${formatMoney(reqs.minRevenue)}`, met: totalRevenue >= reqs.minRevenue }] : []),
            ...(reqs.minUsers ? [{ label: `Subscribers: ${formatNumber(subscribers)} / ${formatNumber(reqs.minUsers)}`, met: subscribers >= reqs.minUsers }] : []),
            ...(reqs.minReputation ? [{ label: `Reputation: ${reputationScore} / ${reqs.minReputation}`, met: reputationScore >= reqs.minReputation }] : []),
          ];
          return (
            <div className="bg-surface-800 rounded-lg p-4 mb-4 border border-surface-600">
              <div className="flex items-center justify-between mb-2">
                <h4 className="font-semibold text-sm capitalize">
                  {fundingStatus.nextRound === 'ipo' ? 'IPO' : fundingStatus.nextRound.replace('series', 'Series ')}
                </h4>
                {fundingStatus.canRaise && (
                  <button
                    onClick={() => raiseFunding(fundingStatus.nextRound!)}
                    className="flex items-center gap-1.5 bg-accent hover:bg-accent-dark text-white rounded-lg px-4 py-2 text-sm font-medium"
                  >
                    <Rocket size={14} />
                    Raise {formatMoney(roundConfig.amount)}
                  </button>
                )}
              </div>
              {checks.length > 0 && (
                <div className="space-y-1.5 mt-2">
                  {checks.map((c, i) => (
                    <div key={i} className="flex items-center gap-2 text-xs">
                      {c.met ? <Check size={12} className="text-success shrink-0" /> : <XIcon size={12} className="text-danger shrink-0" />}
                      <span className={c.met ? 'text-surface-400' : 'text-surface-200'}>{c.label}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })()}

        {funding.completedRounds.length === 0 ? (
          <p className="text-sm text-surface-500">No funding rounds completed yet.</p>
        ) : (
          <div className="space-y-2">
            {funding.completedRounds.map((round, i) => (
              <div key={i} className="bg-surface-800 rounded-lg p-3 flex items-center justify-between">
                <span className="text-sm font-medium capitalize">
                  {round.type === 'ipo' ? 'IPO' : round.type.replace('series', 'Series ')}
                </span>
                <div className="flex items-center gap-4 text-sm">
                  <span className="font-mono text-success">{formatMoney(round.amount)}</span>
                  <span className="text-surface-400">{formatPercent(round.dilution)} dilution</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function FinanceCard({ icon: Icon, label, value, color }: {
  icon: typeof DollarSign;
  label: string;
  value: string;
  color: string;
}) {
  return (
    <div className="bg-surface-900 border border-surface-700 rounded-xl p-4">
      <div className="flex items-center gap-2 mb-2">
        <Icon size={16} className={color} />
        <span className="text-xs text-surface-400 uppercase">{label}</span>
      </div>
      <div className="text-xl font-bold font-mono">{value}</div>
    </div>
  );
}
