import { useState, useEffect, useContext } from 'react'
import { DollarSign, TrendingUp, TrendingDown, Wallet, Landmark, Eye, MousePointer, Target, Briefcase, ArrowRight, Receipt } from 'lucide-react'
import { Link } from 'react-router-dom'
import { AppContext } from '../App'
import { api } from '../utils/api'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'
import StatusBadge from '../components/StatusBadge'
import { SkeletonStatCard, SkeletonTable } from '../components/SkeletonLoader'

function FinanceStatCard({ icon: Icon, label, value, sub, color = 'text-text-primary', bgColor = 'bg-white' }) {
  return (
    <div className={`${bgColor} rounded-xl border border-border p-5`}>
      <div className="flex items-center gap-2 mb-2">
        <div className={`p-2 rounded-lg ${color.replace('text-', 'bg-')}/10`}>
          <Icon className={`w-5 h-5 ${color}`} />
        </div>
        <span className="text-xs uppercase tracking-wider text-text-tertiary font-medium">{label}</span>
      </div>
      <div className={`text-2xl font-bold ${color}`}>{value}</div>
      {sub && <div className="text-xs text-text-tertiary mt-1">{sub}</div>}
    </div>
  )
}

function ProgressRing({ pct, size = 80, stroke = 8, color = '#10b981' }) {
  const r = (size - stroke) / 2
  const circ = 2 * Math.PI * r
  const offset = circ - (Math.min(pct, 100) / 100) * circ
  return (
    <svg width={size} height={size} className="transform -rotate-90">
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#f3f4f6" strokeWidth={stroke} />
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={stroke}
        strokeDasharray={circ} strokeDashoffset={offset} strokeLinecap="round" className="transition-all duration-500" />
      <text x={size / 2} y={size / 2} textAnchor="middle" dominantBaseline="central"
        className="fill-text-primary text-sm font-bold" transform={`rotate(90 ${size / 2} ${size / 2})`}>
        {Math.round(pct)}%
      </text>
    </svg>
  )
}

export default function Finance() {
  const { brands } = useContext(AppContext)
  const { permissions } = useAuth()
  const { currencySymbol } = useLanguage()
  const [summary, setSummary] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => { loadAll() }, [])

  const loadAll = async () => {
    try {
      const sum = await api.get('/finance/summary')
      setSummary(sum.data || sum || {})
    } catch (err) {
      console.error('Failed to load finance:', err)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
          {[1, 2, 3, 4, 5].map(i => <SkeletonStatCard key={i} />)}
        </div>
        <SkeletonTable rows={5} cols={7} />
      </div>
    )
  }

  const s = summary || {}
  const totalReceived = s.totalReceived || 0
  const totalSpent = s.spent || 0
  const remaining = s.remaining || 0
  const totalRevenue = s.revenue || 0
  const roi = s.roi || 0
  const totalExpenses = s.totalExpenses || 0
  const spendPct = totalReceived > 0 ? (totalSpent / totalReceived) * 100 : 0
  const totalCampaignBudget = s.totalCampaignBudget || 0
  const totalProjectBudget = s.totalProjectBudget || 0
  const unallocated = s.unallocated ?? (totalReceived - totalCampaignBudget - totalProjectBudget)
  const campaignPct = totalReceived > 0 ? (totalCampaignBudget / totalReceived) * 100 : 0
  const projectPct = totalReceived > 0 ? (totalProjectBudget / totalReceived) * 100 : 0
  const unallocatedPct = totalReceived > 0 ? (Math.max(0, unallocated) / totalReceived) * 100 : 0

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Top metrics */}
      <div className={`grid grid-cols-2 ${totalExpenses > 0 ? 'lg:grid-cols-6' : 'lg:grid-cols-5'} gap-4 stagger-children`}>
        <FinanceStatCard icon={Wallet} label="Total Received" value={`${totalReceived.toLocaleString()} ${currencySymbol}`} color="text-blue-600" />
        <FinanceStatCard icon={TrendingUp} label="Total Spent" value={`${totalSpent.toLocaleString()} ${currencySymbol}`} sub={`${spendPct.toFixed(1)}% of budget`} color="text-amber-600" />
        {totalExpenses > 0 && (
          <FinanceStatCard icon={Receipt} label="Expenses" value={`${totalExpenses.toLocaleString()} ${currencySymbol}`} color="text-red-600" />
        )}
        <FinanceStatCard icon={Landmark} label="Remaining" value={`${remaining.toLocaleString()} ${currencySymbol}`} color={remaining >= 0 ? 'text-emerald-600' : 'text-red-600'} />
        <FinanceStatCard icon={DollarSign} label="Revenue" value={`${totalRevenue.toLocaleString()} ${currencySymbol}`} color="text-purple-600" />
        <FinanceStatCard icon={roi >= 0 ? TrendingUp : TrendingDown} label="Global ROI"
          value={`${roi.toFixed(1)}%`}
          color={roi >= 0 ? 'text-emerald-600' : 'text-red-600'} />
      </div>

      {/* Budget allocation bar */}
      {totalReceived > 0 && (
        <div className="section-card p-5">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-xs uppercase tracking-wider text-text-tertiary font-medium">Budget Allocation</h3>
            <Link to="/budgets" className="text-xs text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
              Manage Budgets <ArrowRight className="w-3 h-3" />
            </Link>
          </div>
          <div className="h-4 bg-surface-tertiary rounded-full overflow-hidden flex">
            {campaignPct > 0 && (
              <div className="h-full bg-blue-500 transition-all" style={{ width: `${campaignPct}%` }} title={`Campaigns: ${totalCampaignBudget.toLocaleString()} ${currencySymbol}`} />
            )}
            {projectPct > 0 && (
              <div className="h-full bg-purple-500 transition-all" style={{ width: `${projectPct}%` }} title={`Projects: ${totalProjectBudget.toLocaleString()} ${currencySymbol}`} />
            )}
          </div>
          <div className="flex items-center gap-4 mt-2.5 text-xs">
            <div className="flex items-center gap-1.5">
              <div className="w-2.5 h-2.5 rounded-full bg-blue-500" />
              <span className="text-text-secondary">Campaigns: <span className="font-semibold text-text-primary">{totalCampaignBudget.toLocaleString()} {currencySymbol}</span></span>
              <span className="text-text-tertiary">({campaignPct.toFixed(0)}%)</span>
            </div>
            <div className="flex items-center gap-1.5">
              <div className="w-2.5 h-2.5 rounded-full bg-purple-500" />
              <span className="text-text-secondary">Projects: <span className="font-semibold text-text-primary">{totalProjectBudget.toLocaleString()} {currencySymbol}</span></span>
              <span className="text-text-tertiary">({projectPct.toFixed(0)}%)</span>
            </div>
            <div className="flex items-center gap-1.5">
              <div className="w-2.5 h-2.5 rounded-full bg-gray-300" />
              <span className="text-text-secondary">Unallocated: <span className="font-semibold text-text-primary">{Math.max(0, unallocated).toLocaleString()} {currencySymbol}</span></span>
              <span className="text-text-tertiary">({unallocatedPct.toFixed(0)}%)</span>
            </div>
          </div>
        </div>
      )}

      {/* Budget utilization + Global metrics */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Utilization ring */}
        <div className="section-card p-5 flex flex-col items-center justify-center">
          <h3 className="text-xs uppercase tracking-wider text-text-tertiary font-medium mb-4">Budget Utilization</h3>
          <ProgressRing
            pct={spendPct}
            size={120}
            stroke={10}
            color={spendPct > 90 ? '#ef4444' : spendPct > 70 ? '#f59e0b' : '#10b981'}
          />
          <div className="text-xs text-text-tertiary mt-3">
            {totalSpent.toLocaleString()} of {totalReceived.toLocaleString()} {currencySymbol}
          </div>
        </div>

        {/* Global performance */}
        <div className="section-card p-5 lg:col-span-2">
          <h3 className="text-xs uppercase tracking-wider text-text-tertiary font-medium mb-4">Global Performance</h3>
          <div className="grid grid-cols-3 gap-6">
            <div className="text-center">
              <Eye className="w-5 h-5 mx-auto mb-1 text-purple-500" />
              <div className="text-xl font-bold text-text-primary">{(s.impressions || 0).toLocaleString()}</div>
              <div className="text-xs text-text-tertiary">Impressions</div>
            </div>
            <div className="text-center">
              <MousePointer className="w-5 h-5 mx-auto mb-1 text-blue-500" />
              <div className="text-xl font-bold text-text-primary">{(s.clicks || 0).toLocaleString()}</div>
              <div className="text-xs text-text-tertiary">Clicks</div>
              {s.clicks > 0 && s.spent > 0 && (
                <div className="text-[10px] text-text-tertiary mt-0.5">CPC: {(s.spent / s.clicks).toFixed(2)} {currencySymbol}</div>
              )}
            </div>
            <div className="text-center">
              <Target className="w-5 h-5 mx-auto mb-1 text-emerald-500" />
              <div className="text-xl font-bold text-text-primary">{(s.conversions || 0).toLocaleString()}</div>
              <div className="text-xs text-text-tertiary">Conversions</div>
              {s.conversions > 0 && s.spent > 0 && (
                <div className="text-[10px] text-text-tertiary mt-0.5">CPA: {(s.spent / s.conversions).toFixed(2)} {currencySymbol}</div>
              )}
            </div>
          </div>
          {s.impressions > 0 && s.clicks > 0 && (
            <div className="mt-4 pt-3 border-t border-border text-center">
              <span className="text-xs text-text-tertiary">
                CTR: {(s.clicks / s.impressions * 100).toFixed(2)}%
                {s.conversions > 0 && s.clicks > 0 && ` · Conv. Rate: ${(s.conversions / s.clicks * 100).toFixed(2)}%`}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Per-campaign breakdown */}
      {s.campaigns && s.campaigns.length > 0 && (
        <div className="section-card">
          <div className="section-card-header flex items-center gap-3">
            <div className="p-2 rounded-lg bg-blue-50">
              <Target className="w-4 h-4 text-blue-600" />
            </div>
            <div>
              <h3 className="font-semibold text-text-primary text-base">Campaign Breakdown</h3>
              <p className="text-xs text-text-tertiary mt-0.5">{s.campaigns.length} campaigns &middot; Track-level budget allocation</p>
            </div>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-surface-secondary">
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">Campaign</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Budget Assigned</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Track Allocated</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Spent</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Expenses</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Revenue</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">ROI</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-text-tertiary">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border-light">
                {s.campaigns.map(c => {
                  const totalCampaignConsumed = c.tracks_spent + (c.expenses || 0)
                  const cRoi = totalCampaignConsumed > 0 ? ((c.tracks_revenue - totalCampaignConsumed) / totalCampaignConsumed * 100) : 0
                  return (
                    <tr key={c.id} className="hover:bg-surface-secondary">
                      <td className="px-4 py-3 font-medium text-text-primary">{c.name}</td>
                      <td className="px-4 py-3 text-right">
                        {c.budget_from_entries > 0 ? (
                          <span className="font-semibold text-blue-600">{c.budget_from_entries.toLocaleString()}</span>
                        ) : <span className="text-text-tertiary">{'\u2014'}</span>}
                      </td>
                      <td className="px-4 py-3 text-right text-text-secondary">{c.tracks_allocated.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right text-text-secondary">{c.tracks_spent.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right">
                        {c.expenses > 0 ? (
                          <span className="font-semibold text-red-500">-{c.expenses.toLocaleString()}</span>
                        ) : <span className="text-text-tertiary">{'\u2014'}</span>}
                      </td>
                      <td className="px-4 py-3 text-right text-text-secondary">{c.tracks_revenue.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right">
                        {totalCampaignConsumed > 0 ? (
                          <span className={`text-xs font-semibold px-1.5 py-0.5 rounded ${cRoi >= 0 ? 'text-emerald-600 bg-emerald-50' : 'text-red-600 bg-red-50'}`}>
                            {cRoi.toFixed(0)}%
                          </span>
                        ) : '\u2014'}
                      </td>
                      <td className="px-4 py-3 text-center"><StatusBadge status={c.status} size="xs" /></td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Allocated Funds breakdown */}
      {s.projects && s.projects.filter(p => p.budget_allocated > 0 || p.expenses > 0).length > 0 && (
        <div className="section-card">
          <div className="section-card-header flex items-center gap-3">
            <div className="p-2 rounded-lg bg-purple-50">
              <Briefcase className="w-4 h-4 text-purple-600" />
            </div>
            <div>
              <h3 className="font-semibold text-text-primary text-base">Allocated Funds</h3>
              <p className="text-xs text-text-tertiary mt-0.5">{s.projects.filter(p => p.budget_allocated > 0 || p.expenses > 0).length} work orders with assigned budget</p>
            </div>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-surface-secondary">
                  <th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary">Work Order</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Budget Allocated</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-text-tertiary">Expenses</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-text-tertiary">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border-light">
                {s.projects.filter(p => p.budget_allocated > 0 || p.expenses > 0).map(p => (
                  <tr key={p.id} className="hover:bg-surface-secondary">
                    <td className="px-4 py-3 font-medium text-text-primary">{p.name}</td>
                    <td className="px-4 py-3 text-right text-text-secondary">{p.budget_allocated.toLocaleString()} {currencySymbol}</td>
                    <td className="px-4 py-3 text-right">
                      {p.expenses > 0 ? (
                        <span className="font-semibold text-red-500">-{p.expenses.toLocaleString()}</span>
                      ) : <span className="text-text-tertiary">{'\u2014'}</span>}
                    </td>
                    <td className="px-4 py-3 text-center"><StatusBadge status={p.status} size="xs" /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
