import React, { useState } from 'react';

const FundingStackModel = () => {
  const [selectedPhase, setSelectedPhase] = useState(1);
  const [showDetail, setShowDetail] = useState(null);

  const phases = {
    1: {
      name: "Land & Foundation",
      timeline: "2026-2027",
      total: 1850000,
      sources: [
        { name: "FSA Farm Ownership Loan", amount: 600000, type: "debt", rate: "3.25%", term: "40 years", agency: "USDA FSA" },
        { name: "FSA Beginning Farmer Down Payment", amount: 300000, type: "grant-loan", rate: "1.5%", term: "20 years", agency: "USDA FSA" },
        { name: "UAIP Planning Grant", amount: 100000, type: "grant", agency: "USDA NIFA" },
        { name: "SARE Farmer Grant", amount: 30000, type: "grant", agency: "USDA SARE" },
        { name: "EQIP Conservation", amount: 75000, type: "cost-share", match: "10%", agency: "USDA NRCS" },
        { name: "State Ag Development Grant", amount: 50000, type: "grant", agency: "MA DAR" },
        { name: "Owner Equity / Seed Capital", amount: 150000, type: "equity" },
        { name: "FSA Operating Loan", amount: 400000, type: "debt", rate: "4.5%", term: "7 years", agency: "USDA FSA" },
        { name: "Microloan Reserve", amount: 50000, type: "debt", rate: "5%", agency: "USDA FSA" },
        { name: "Additional Working Capital", amount: 95000, type: "debt" },
      ],
      uses: [
        { name: "Land Acquisition (45 acres)", amount: 900000 },
        { name: "Site Development & Infrastructure", amount: 250000 },
        { name: "Aquaponics Containers (7)", amount: 350000 },
        { name: "Solar Array (850 kW)", amount: 200000 },
        { name: "Working Capital & Reserves", amount: 150000 },
      ]
    },
    2: {
      name: "Housing Development",
      timeline: "2027-2028",
      total: 5750000,
      sources: [
        { name: "USDA Community Facilities Loan", amount: 3500000, type: "debt", rate: "3.5%", term: "40 years", agency: "USDA RD" },
        { name: "USDA Community Facilities Grant", amount: 750000, type: "grant", agency: "USDA RD" },
        { name: "MassHousing Affordable Loan", amount: 500000, type: "debt", rate: "4%", agency: "MassHousing" },
        { name: "REAP Solar/Energy Grant", amount: 250000, type: "grant", agency: "USDA RD" },
        { name: "UAIP Implementation Grant", amount: 400000, type: "grant", agency: "USDA NIFA" },
        { name: "CDBG Housing", amount: 200000, type: "grant", agency: "HUD via MA" },
        { name: "Developer Fee / Retained", amount: 150000, type: "equity" },
      ],
      uses: [
        { name: "50 Triple Trio Units", amount: 4250000 },
        { name: "Community Hub Building", amount: 500000 },
        { name: "Site Infrastructure (roads, utilities)", amount: 400000 },
        { name: "Permaculture & Food Forest Install", amount: 150000 },
        { name: "Contingency & Soft Costs", amount: 450000 },
      ]
    },
    3: {
      name: "Amenities & Revenue",
      timeline: "2028-2029",
      total: 1400000,
      sources: [
        { name: "NMTC Allocation (effective subsidy)", amount: 400000, type: "tax-credit", agency: "Treasury/CDE" },
        { name: "Corporate Sponsorship Package", amount: 250000, type: "sponsorship", notes: "Naming rights, signage" },
        { name: "Foundation Grants (ag education)", amount: 150000, type: "grant" },
        { name: "Capital Campaign / Community", amount: 200000, type: "donations" },
        { name: "Pre-sales / Member Deposits", amount: 250000, type: "pre-revenue" },
        { name: "Additional CF Loan Draw", amount: 150000, type: "debt" },
      ],
      uses: [
        { name: "Community Kitchen / Processing", amount: 350000 },
        { name: "Event & Education Spaces", amount: 300000 },
        { name: "Trail System & Recreation", amount: 150000 },
        { name: "Equipment & Operations Setup", amount: 200000 },
        { name: "Marketing & Lease-up Costs", amount: 150000 },
        { name: "Operating Reserve Fund", amount: 250000 },
      ]
    }
  };

  const getTotalByType = (sources, type) => {
    return sources.filter(s => s.type === type).reduce((sum, s) => sum + s.amount, 0);
  };

  const getTypeColor = (type) => {
    switch(type) {
      case 'grant': return '#22c55e';
      case 'grant-loan': return '#84cc16';
      case 'debt': return '#3b82f6';
      case 'equity': return '#f59e0b';
      case 'cost-share': return '#10b981';
      case 'tax-credit': return '#8b5cf6';
      case 'sponsorship': return '#ec4899';
      case 'donations': return '#f97316';
      case 'pre-revenue': return '#06b6d4';
      default: return '#64748b';
    }
  };

  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(amount);
  };

  const grandTotal = Object.values(phases).reduce((sum, p) => sum + p.total, 0);
  
  // Calculate totals across all phases
  const allSources = Object.values(phases).flatMap(p => p.sources);
  const totalGrants = allSources.filter(s => ['grant', 'cost-share', 'tax-credit'].includes(s.type)).reduce((sum, s) => sum + s.amount, 0);
  const totalDebt = allSources.filter(s => s.type === 'debt' || s.type === 'grant-loan').reduce((sum, s) => sum + s.amount, 0);
  const totalEquity = allSources.filter(s => ['equity', 'sponsorship', 'donations', 'pre-revenue'].includes(s.type)).reduce((sum, s) => sum + s.amount, 0);

  return (
    <div className="min-h-screen bg-slate-900 text-white p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-6">
          <h1 className="text-3xl font-bold bg-gradient-to-r from-amber-400 to-emerald-400 bg-clip-text text-transparent mb-2">
            Funding Stack: Town Woods Regenerative Village
          </h1>
          <p className="text-slate-400">50 Units • {formatCurrency(grandTotal)} Total Development • 3-Year Phased Approach</p>
        </div>

        {/* Grand Summary */}
        <div className="grid md:grid-cols-4 gap-4 mb-6">
          <div className="bg-slate-800/50 rounded-xl p-4 border border-slate-700">
            <div className="text-3xl font-bold text-white">{formatCurrency(grandTotal)}</div>
            <div className="text-sm text-slate-400">Total Project Cost</div>
          </div>
          <div className="bg-emerald-500/10 rounded-xl p-4 border border-emerald-500/30">
            <div className="text-3xl font-bold text-emerald-400">{formatCurrency(totalGrants)}</div>
            <div className="text-sm text-slate-400">Grants & Tax Credits</div>
            <div className="text-xs text-emerald-400 mt-1">{((totalGrants/grandTotal)*100).toFixed(0)}% of total</div>
          </div>
          <div className="bg-blue-500/10 rounded-xl p-4 border border-blue-500/30">
            <div className="text-3xl font-bold text-blue-400">{formatCurrency(totalDebt)}</div>
            <div className="text-sm text-slate-400">Low-Interest Debt</div>
            <div className="text-xs text-blue-400 mt-1">{((totalDebt/grandTotal)*100).toFixed(0)}% of total</div>
          </div>
          <div className="bg-amber-500/10 rounded-xl p-4 border border-amber-500/30">
            <div className="text-3xl font-bold text-amber-400">{formatCurrency(totalEquity)}</div>
            <div className="text-sm text-slate-400">Equity & Other</div>
            <div className="text-xs text-amber-400 mt-1">{((totalEquity/grandTotal)*100).toFixed(0)}% of total</div>
          </div>
        </div>

        {/* Phase Tabs */}
        <div className="flex gap-2 mb-6">
          {[1, 2, 3].map(phase => (
            <button
              key={phase}
              onClick={() => setSelectedPhase(phase)}
              className={`flex-1 p-4 rounded-xl border transition-all ${
                selectedPhase === phase 
                  ? 'bg-slate-700 border-cyan-500 shadow-lg shadow-cyan-500/20' 
                  : 'bg-slate-800/50 border-slate-700 hover:border-slate-600'
              }`}
            >
              <div className="text-lg font-bold text-cyan-400">Phase {phase}</div>
              <div className="text-sm text-slate-300">{phases[phase].name}</div>
              <div className="text-xs text-slate-500">{phases[phase].timeline}</div>
              <div className="text-lg font-mono text-amber-400 mt-2">{formatCurrency(phases[phase].total)}</div>
            </button>
          ))}
        </div>

        {/* Phase Detail */}
        <div className="grid lg:grid-cols-2 gap-6 mb-6">
          
          {/* Sources of Funds */}
          <div className="bg-slate-800/50 rounded-xl p-5 border border-slate-700">
            <h2 className="text-lg font-bold text-emerald-400 mb-4">Sources of Funds</h2>
            
            <div className="space-y-2">
              {phases[selectedPhase].sources.map((source, idx) => (
                <div 
                  key={idx}
                  onClick={() => setShowDetail(showDetail === idx ? null : idx)}
                  className="cursor-pointer"
                >
                  <div className="flex items-center gap-3 p-2 rounded-lg hover:bg-slate-700/50 transition-colors">
                    <div 
                      className="w-3 h-3 rounded-full flex-shrink-0"
                      style={{ backgroundColor: getTypeColor(source.type) }}
                    />
                    <div className="flex-grow">
                      <div className="flex justify-between items-center">
                        <span className="text-sm text-slate-300">{source.name}</span>
                        <span className="font-mono text-sm" style={{ color: getTypeColor(source.type) }}>
                          {formatCurrency(source.amount)}
                        </span>
                      </div>
                      {/* Progress bar */}
                      <div className="w-full h-1.5 bg-slate-700 rounded-full mt-1">
                        <div 
                          className="h-full rounded-full"
                          style={{ 
                            width: `${(source.amount / phases[selectedPhase].total) * 100}%`,
                            backgroundColor: getTypeColor(source.type)
                          }}
                        />
                      </div>
                    </div>
                  </div>
                  
                  {/* Expanded detail */}
                  {showDetail === idx && (
                    <div className="ml-6 p-3 bg-slate-900/50 rounded-lg text-xs space-y-1 border-l-2" 
                         style={{ borderColor: getTypeColor(source.type) }}>
                      <div className="flex justify-between">
                        <span className="text-slate-500">Type</span>
                        <span className="text-slate-300 capitalize">{source.type.replace('-', ' ')}</span>
                      </div>
                      {source.agency && (
                        <div className="flex justify-between">
                          <span className="text-slate-500">Agency</span>
                          <span className="text-slate-300">{source.agency}</span>
                        </div>
                      )}
                      {source.rate && (
                        <div className="flex justify-between">
                          <span className="text-slate-500">Interest Rate</span>
                          <span className="text-emerald-400">{source.rate}</span>
                        </div>
                      )}
                      {source.term && (
                        <div className="flex justify-between">
                          <span className="text-slate-500">Term</span>
                          <span className="text-slate-300">{source.term}</span>
                        </div>
                      )}
                      {source.match && (
                        <div className="flex justify-between">
                          <span className="text-slate-500">Match Required</span>
                          <span className="text-slate-300">{source.match}</span>
                        </div>
                      )}
                      {source.notes && (
                        <div className="flex justify-between">
                          <span className="text-slate-500">Notes</span>
                          <span className="text-slate-300">{source.notes}</span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>

            {/* Phase totals by type */}
            <div className="mt-4 pt-4 border-t border-slate-700 grid grid-cols-3 gap-2 text-xs">
              <div className="text-center p-2 bg-emerald-500/10 rounded">
                <div className="text-emerald-400 font-mono">{formatCurrency(getTotalByType(phases[selectedPhase].sources, 'grant') + getTotalByType(phases[selectedPhase].sources, 'cost-share'))}</div>
                <div className="text-slate-500">Grants</div>
              </div>
              <div className="text-center p-2 bg-blue-500/10 rounded">
                <div className="text-blue-400 font-mono">{formatCurrency(getTotalByType(phases[selectedPhase].sources, 'debt') + getTotalByType(phases[selectedPhase].sources, 'grant-loan'))}</div>
                <div className="text-slate-500">Debt</div>
              </div>
              <div className="text-center p-2 bg-amber-500/10 rounded">
                <div className="text-amber-400 font-mono">{formatCurrency(getTotalByType(phases[selectedPhase].sources, 'equity') + getTotalByType(phases[selectedPhase].sources, 'sponsorship') + getTotalByType(phases[selectedPhase].sources, 'donations') + getTotalByType(phases[selectedPhase].sources, 'pre-revenue'))}</div>
                <div className="text-slate-500">Equity/Other</div>
              </div>
            </div>
          </div>

          {/* Uses of Funds */}
          <div className="bg-slate-800/50 rounded-xl p-5 border border-slate-700">
            <h2 className="text-lg font-bold text-amber-400 mb-4">Uses of Funds</h2>
            
            <div className="space-y-3">
              {phases[selectedPhase].uses.map((use, idx) => (
                <div key={idx}>
                  <div className="flex justify-between items-center mb-1">
                    <span className="text-sm text-slate-300">{use.name}</span>
                    <span className="font-mono text-sm text-amber-400">{formatCurrency(use.amount)}</span>
                  </div>
                  <div className="w-full h-2 bg-slate-700 rounded-full">
                    <div 
                      className="h-full rounded-full bg-gradient-to-r from-amber-500 to-orange-500"
                      style={{ width: `${(use.amount / phases[selectedPhase].total) * 100}%` }}
                    />
                  </div>
                </div>
              ))}
            </div>

            {/* Total check */}
            <div className="mt-4 pt-4 border-t border-slate-700">
              <div className="flex justify-between items-center">
                <span className="text-slate-400">Phase {selectedPhase} Total</span>
                <span className="font-mono text-lg text-amber-400">{formatCurrency(phases[selectedPhase].total)}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Capital Stack Visualization */}
        <div className="bg-slate-800/50 rounded-xl p-6 border border-slate-700 mb-6">
          <h2 className="text-lg font-bold text-purple-400 mb-4">Capital Stack Visualization</h2>
          
          <div className="flex gap-4 items-end h-64">
            {[1, 2, 3].map(phase => {
              const p = phases[phase];
              const grants = p.sources.filter(s => ['grant', 'cost-share', 'tax-credit'].includes(s.type)).reduce((sum, s) => sum + s.amount, 0);
              const debt = p.sources.filter(s => s.type === 'debt' || s.type === 'grant-loan').reduce((sum, s) => sum + s.amount, 0);
              const equity = p.sources.filter(s => ['equity', 'sponsorship', 'donations', 'pre-revenue'].includes(s.type)).reduce((sum, s) => sum + s.amount, 0);
              const maxHeight = 240;
              const scale = maxHeight / Math.max(...Object.values(phases).map(ph => ph.total));
              
              return (
                <div key={phase} className="flex-1">
                  <div 
                    className={`rounded-t-lg overflow-hidden transition-all ${selectedPhase === phase ? 'ring-2 ring-cyan-400' : ''}`}
                    style={{ height: p.total * scale }}
                    onClick={() => setSelectedPhase(phase)}
                  >
                    {/* Grants layer */}
                    <div 
                      className="w-full bg-emerald-500/80 flex items-center justify-center"
                      style={{ height: grants * scale }}
                    >
                      {grants > 200000 && <span className="text-xs text-white font-mono">{formatCurrency(grants)}</span>}
                    </div>
                    {/* Debt layer */}
                    <div 
                      className="w-full bg-blue-500/80 flex items-center justify-center"
                      style={{ height: debt * scale }}
                    >
                      {debt > 200000 && <span className="text-xs text-white font-mono">{formatCurrency(debt)}</span>}
                    </div>
                    {/* Equity layer */}
                    <div 
                      className="w-full bg-amber-500/80 flex items-center justify-center"
                      style={{ height: equity * scale }}
                    >
                      {equity > 200000 && <span className="text-xs text-white font-mono">{formatCurrency(equity)}</span>}
                    </div>
                  </div>
                  <div className="text-center mt-2">
                    <div className="text-sm font-medium text-slate-300">Phase {phase}</div>
                    <div className="text-xs text-slate-500">{p.timeline}</div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Legend */}
          <div className="flex justify-center gap-6 mt-4 text-sm">
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded bg-emerald-500/80"></div>
              <span className="text-slate-400">Grants & Tax Credits</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded bg-blue-500/80"></div>
              <span className="text-slate-400">Low-Interest Debt</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-4 h-4 rounded bg-amber-500/80"></div>
              <span className="text-slate-400">Equity & Other</span>
            </div>
          </div>
        </div>

        {/* Key Programs Reference */}
        <div className="bg-gradient-to-br from-slate-800/50 to-blue-900/20 rounded-xl p-6 border border-blue-500/30">
          <h2 className="text-lg font-bold text-blue-400 mb-4">Key Funding Programs</h2>
          
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4 text-sm">
            <div className="bg-slate-900/50 p-4 rounded-lg">
              <div className="text-cyan-400 font-bold mb-2">USDA FSA Loans</div>
              <ul className="space-y-1 text-slate-400">
                <li>• Farm Ownership: Up to $600K</li>
                <li>• Beginning Farmer Down Payment</li>
                <li>• Operating Loans: Up to $400K</li>
                <li>• Contact: Carroll County FSA</li>
              </ul>
            </div>
            
            <div className="bg-slate-900/50 p-4 rounded-lg">
              <div className="text-emerald-400 font-bold mb-2">USDA Grants</div>
              <ul className="space-y-1 text-slate-400">
                <li>• UAIP: Up to $500K implementation</li>
                <li>• SARE: Up to $30K farmer research</li>
                <li>• VAPG: Up to $250K value-added</li>
                <li>• REAP: Up to $500K renewable energy</li>
              </ul>
            </div>
            
            <div className="bg-slate-900/50 p-4 rounded-lg">
              <div className="text-purple-400 font-bold mb-2">Community Facilities</div>
              <ul className="space-y-1 text-slate-400">
                <li>• Loans: Up to 100% of project</li>
                <li>• Grants: Up to 75% (low-income areas)</li>
                <li>• 40-year terms, ~3.5% rate</li>
                <li>• Contact: USDA RD NH/VT Office</li>
              </ul>
            </div>
            
            <div className="bg-slate-900/50 p-4 rounded-lg">
              <div className="text-pink-400 font-bold mb-2">Tax Credits</div>
              <ul className="space-y-1 text-slate-400">
                <li>• NMTC: ~20% effective subsidy</li>
                <li>• ITC: 30% solar investment credit</li>
                <li>• LIHTC: If affordable housing</li>
                <li>• Contact: NH Community Loan Fund</li>
              </ul>
            </div>
            
            <div className="bg-slate-900/50 p-4 rounded-lg">
              <div className="text-amber-400 font-bold mb-2">State Programs</div>
              <ul className="space-y-1 text-slate-400">
                <li>• MassHousing loans</li>
                <li>• MassDevelopment incentives</li>
                <li>• CDBG via state allocation</li>
                <li>• MA DAR agricultural grants</li>
              </ul>
            </div>
            
            <div className="bg-slate-900/50 p-4 rounded-lg">
              <div className="text-orange-400 font-bold mb-2">Private Capital</div>
              <ul className="space-y-1 text-slate-400">
                <li>• Corporate sponsorships</li>
                <li>• Foundation grants (ag education)</li>
                <li>• Community capital campaign</li>
                <li>• Pre-sales & member deposits</li>
              </ul>
            </div>
          </div>
        </div>

        <p className="text-center text-slate-500 text-xs mt-6">Click funding sources for details • Capital Stack Model v1</p>
      </div>
    </div>
  );
};

export default FundingStackModel;
