import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { toast } from 'react-hot-toast';
import { 
  Wallet, 
  TrendUp, 
  TrendDown, 
  Buildings, 
  HandCoins, 
  ArrowsLeftRight,
  CurrencyDollar,
  Building,
  Users,
  Calendar,
  Funnel
} from '@phosphor-icons/react';
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';

const SuperAdminDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);
  const [viewMode, setViewMode] = useState('current'); // 'current' or 'date_range'
  const [dateRange, setDateRange] = useState({ from: '', to: '' });

  useEffect(() => {
    loadDashboard();
  }, [viewMode, dateRange]);

  const loadDashboard = async () => {
    setLoading(true);
    try {
      const params = viewMode === 'date_range' ? {
        from_date: dateRange.from,
        to_date: dateRange.to
      } : {};
      const res = await axios.get('/api/dashboard/super-admin', { params });
      setData(res.data);
    } catch (e) {
      console.error('Dashboard error:', e);
      toast.error(e.response?.data?.message || 'Failed to load dashboard');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-gray-500 mb-4">Unable to load dashboard data</p>
          <button
            onClick={loadDashboard}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  const { financials, bank_accounts, companies, loans, sweeps, historical } = data;

  const COLORS = ['#5D4037', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Super Admin Dashboard</h1>
          <p className="text-gray-500">Financial overview and management</p>
        </div>
        <div className="text-sm text-gray-500">
          {financials.year_month}
        </div>
      </div>

      {/* Date Filter */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
        <div className="flex items-center justify-between">
          <div className="flex gap-2">
            <button
              onClick={() => setViewMode('current')}
              className={`px-4 py-2 rounded-lg font-medium transition-all ${
                viewMode === 'current'
                  ? 'bg-primary-600 text-white shadow-md'
                  : 'text-gray-600 hover:bg-gray-100'
              }`}
            >
              Current Month
            </button>
            <button
              onClick={() => setViewMode('date_range')}
              className={`px-4 py-2 rounded-lg font-medium transition-all ${
                viewMode === 'date_range'
                  ? 'bg-primary-600 text-white shadow-md'
                  : 'text-gray-600 hover:bg-gray-100'
              }`}
            >
              Date Range
            </button>
          </div>
          {viewMode === 'date_range' && (
            <div className="flex gap-2">
              <input
                type="date"
                value={dateRange.from}
                onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
              <input
                type="date"
                value={dateRange.to}
                onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
            </div>
          )}
        </div>
      </div>

      {/* Financial Summary Cards (clean, consistent) */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100 h-36 flex flex-col justify-between">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 rounded-lg bg-green-50 flex items-center justify-center">
              <TrendUp size={22} className="text-green-600" />
            </div>
            <span className="text-xs text-gray-500">Revenue</span>
          </div>
          <div>
            <p className="text-2xl font-bold text-gray-900">₦{Number(financials.revenue).toLocaleString()}</p>
            <p className="text-xs text-gray-400 mt-1">Profit sweeps + loan repayments</p>
          </div>
        </div>

        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100 h-36 flex flex-col justify-between">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 rounded-lg bg-red-50 flex items-center justify-center">
              <TrendDown size={22} className="text-red-600" />
            </div>
            <span className="text-xs text-gray-500">Expenses</span>
          </div>
          <div>
            <p className="text-2xl font-bold text-gray-900">₦{Number(financials.expenses).toLocaleString()}</p>
            <p className="text-xs text-gray-400 mt-1">Loan disbursements & outgoing</p>
          </div>
        </div>

        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100 h-36 flex flex-col justify-between">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 rounded-lg bg-primary-50 flex items-center justify-center">
              <Wallet size={22} className="text-primary-600" />
            </div>
            <span className="text-xs text-gray-500">Net Profit</span>
          </div>
          <div>
            <p className={`text-2xl font-bold ${financials.net_profit >= 0 ? 'text-green-600' : 'text-red-600'}`}>
              ₦{Number(financials.net_profit).toLocaleString()}
            </p>
            <p className="text-xs text-gray-400 mt-1">Current period</p>
          </div>
        </div>

        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100 h-36 flex flex-col justify-between">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 rounded-lg bg-purple-50 flex items-center justify-center">
              <CurrencyDollar size={22} className="text-purple-600" />
            </div>
            <span className="text-xs text-gray-500">Cash Balance</span>
          </div>
          <div>
            <p className="text-2xl font-bold text-gray-900">₦{Number(financials.cash_balance).toLocaleString()}</p>
            <p className="text-xs text-gray-400 mt-1">Available cash</p>
          </div>
        </div>
      </div>

      {/* Charts Section: large chart left, compact panels right */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Revenue vs Expenses (6 Months)</h2>
          <ResponsiveContainer width="100%" height={360}>
            <LineChart data={historical} margin={{ top: 10, right: 20, left: -10, bottom: 10 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="month" />
              <YAxis />
              <Tooltip formatter={(value) => `₦${Number(value).toLocaleString()}`} />
              <Legend verticalAlign="top" />
              <Line type="monotone" dataKey="revenue" stroke="#10B981" strokeWidth={2} name="Revenue" dot={false} />
              <Line type="monotone" dataKey="expenses" stroke="#EF4444" strokeWidth={2} name="Expenses" dot={false} />
              <Line type="monotone" dataKey="net_profit" stroke="#5D4037" strokeWidth={2} name="Net Profit" dot={false} />
            </LineChart>
          </ResponsiveContainer>
        </div>

        <div className="space-y-6">
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <h3 className="text-sm font-semibold text-gray-800 mb-3">Company Cash Balances</h3>
            <ResponsiveContainer width="100%" height={120}>
              <BarChart data={companies.companies.slice(0, 6)} layout="vertical" margin={{ left: 10 }}>
                <XAxis type="number" hide />
                <YAxis type="category" dataKey="name" width={120} />
                <Tooltip formatter={(value) => `₦${Number(value).toLocaleString()}`} />
                <Bar dataKey="cash_balance" fill="#5D4037" />
              </BarChart>
            </ResponsiveContainer>
          </div>

          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <h3 className="text-sm font-semibold text-gray-800 mb-3">Total Loaned / Repaid</h3>
            <ResponsiveContainer width="100%" height={120}>
              <BarChart data={[{ name: 'Loaned', value: loans.total_loaned }, { name: 'Repaid', value: loans.total_repaid }]}> 
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip formatter={(value) => `₦${Number(value).toLocaleString()}`} />
                <Bar dataKey="value" fill="#10B981" />
              </BarChart>
            </ResponsiveContainer>
            <p className="text-xs text-gray-500 mt-2">Outstanding: <span className="font-semibold">₦{Number(loans.outstanding).toLocaleString()}</span></p>
          </div>

          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <h3 className="text-sm font-semibold text-gray-800 mb-3">Profit Allocation (Recent)</h3>
            {sweeps.recent && sweeps.recent.length > 0 ? (
              <ResponsiveContainer width="100%" height={160}>
                <PieChart>
                  <Pie
                    data={sweeps.recent.map(s => ({ name: s.from_company?.name || 'Unknown', value: s.actual_amount || s.calculated_amount || 0 })).filter(i => i.value > 0)}
                    cx="50%"
                    cy="50%"
                    outerRadius={60}
                    dataKey="value"
                    labelLine={false}
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  >
                    {COLORS.map((c, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Tooltip formatter={(value) => `₦${Number(value).toLocaleString()}`} />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <p className="text-xs text-gray-400">No recent allocations</p>
            )}
          </div>
        </div>
      </div>

      {/* Bank Accounts & Companies Cash */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Bank Accounts */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">Bank Accounts</h2>
            <span className="text-sm text-gray-500">Total: ₦{Number(bank_accounts.total_balance).toLocaleString()}</span>
          </div>
          {bank_accounts.accounts.length === 0 ? (
            <p className="text-gray-500 text-sm">No bank accounts found</p>
          ) : (
            <div className="space-y-3">
              {bank_accounts.accounts.map((account) => (
                <div key={account.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div>
                    <p className="font-medium text-gray-900">{account.bank_name}</p>
                    <p className="text-xs text-gray-500">{account.account_number} - {account.account_name}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-semibold text-gray-900">₦{Number(account.current_balance).toLocaleString()}</p>
                    {account.is_primary && <span className="text-xs text-primary-600">Primary</span>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Companies Cash Overview */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">Companies Cash</h2>
            <span className="text-sm text-gray-500">Total: ₦{Number(companies.total_cash).toLocaleString()}</span>
          </div>
          {companies.companies.length === 0 ? (
            <p className="text-gray-500 text-sm">No companies found</p>
          ) : (
            <div className="space-y-3 max-h-64 overflow-y-auto">
              {companies.companies.map((company) => (
                <div key={company.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-lg bg-primary-100 flex items-center justify-center">
                      <Building size={20} className="text-primary-600" />
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">{company.name}</p>
                      <p className="text-xs text-gray-500">Profit: ₦{Number(company.net_profit).toLocaleString()}</p>
                    </div>
                  </div>
                  <p className="font-semibold text-gray-900">₦{Number(company.cash_balance).toLocaleString()}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Loans & Sweeps */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Loans Overview */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">Loans</h2>
            <div className="flex items-center gap-2">
              <HandCoins size={20} className="text-primary-600" />
              <span className="text-sm text-gray-500">{loans.active} active</span>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div className="p-3 bg-primary-50 rounded-lg">
              <p className="text-xs text-gray-600">Total Loaned</p>
              <p className="text-lg font-bold text-primary-700">₦{Number(loans.total_loaned).toLocaleString()}</p>
            </div>
            <div className="p-3 bg-green-50 rounded-lg">
              <p className="text-xs text-gray-600">Total Repaid</p>
              <p className="text-lg font-bold text-green-700">₦{Number(loans.total_repaid).toLocaleString()}</p>
            </div>
            <div className="p-3 bg-yellow-50 rounded-lg">
              <p className="text-xs text-gray-600">Total Interest</p>
              <p className="text-lg font-bold text-yellow-700">₦{Number(loans.total_interest || 0).toLocaleString()}</p>
            </div>
          </div>
          <div className="p-3 bg-gray-50 rounded-lg mb-4">
            <p className="text-xs text-gray-600">Outstanding</p>
            <p className="text-lg font-bold text-gray-900">₦{Number(loans.outstanding).toLocaleString()}</p>
          </div>
          <h3 className="text-sm font-semibold text-gray-700 mb-2">Recent Loans</h3>
          {loans.recent.length === 0 ? (
            <p className="text-gray-500 text-sm">No recent loans</p>
          ) : (
            <div className="space-y-2">
              {loans.recent.map((loan) => (
                <div key={loan.id} className="flex items-center justify-between p-2 bg-gray-50 rounded text-sm">
                  <div>
                    <p className="font-medium">{loan.borrower?.name || 'Unknown'}</p>
                    <p className="text-xs text-gray-500">{loan.loan_number}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-semibold">₦{Number(loan.principal_amount).toLocaleString()}</p>
                    <span className={`text-xs px-2 py-0.5 rounded ${
                      loan.status === 'approved' ? 'bg-green-100 text-green-700' :
                      loan.status === 'pending' ? 'bg-yellow-100 text-yellow-700' :
                      'bg-gray-100 text-gray-700'
                    }`}>{loan.status}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Profit Allocation Overview */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">Profit Allocation</h2>
            <div className="flex items-center gap-2">
              <ArrowsLeftRight size={20} className="text-green-600" />
              <span className="text-sm text-gray-500">{sweeps.total_received} received</span>
            </div>
          </div>
          <div className="p-4 bg-green-50 rounded-lg mb-4">
            <p className="text-xs text-gray-600">Total Allocated</p>
            <p className="text-2xl font-bold text-green-700">₦{Number(sweeps.total_swept).toLocaleString()}</p>
          </div>
          <h3 className="text-sm font-semibold text-gray-700 mb-2">Recent Allocations</h3>
          {sweeps.recent.length === 0 ? (
            <p className="text-gray-500 text-sm">No recent allocations</p>
          ) : (
            <div className="space-y-2">
              {sweeps.recent.map((sweep) => (
                <div key={sweep.id} className="flex items-center justify-between p-2 bg-gray-50 rounded text-sm">
                  <div>
                    <p className="font-medium">{sweep.from_company?.name || 'Unknown'}</p>
                    <p className="text-xs text-gray-500">{sweep.year_month}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-semibold">₦{Number(sweep.actual_amount || sweep.calculated_amount).toLocaleString()}</p>
                    <span className={`text-xs px-2 py-0.5 rounded ${
                      sweep.status === 'completed' || sweep.status === 'processed' ? 'bg-green-100 text-green-700' :
                      sweep.status === 'pending' ? 'bg-yellow-100 text-yellow-700' :
                      'bg-gray-100 text-gray-700'
                    }`}>{sweep.status}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default SuperAdminDashboard;
