import React, { useState, useEffect, useCallback } from 'react';
import { LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, AreaChart, Area } from 'recharts';
import { TrendingUp, TrendingDown, DollarSign, Clock, AlertCircle, CheckCircle, Search, RefreshCw, Link, Calendar, FileText, CreditCard, Activity } from 'lucide-react';

// Mock data for disconnected state preview
const MOCK_KPIs = {
  total_revenue: { value: 124500, trend: 'up', trendValue: 12.5 },
  outstanding_amount: { value: 18750, count: 23 },
  overdue_amount: { value: 4200, count: 5 },
  paid_this_month: { value: 45300, trend: 'up', trendValue: 8.3 }
};

const MOCK_REVENUE_DATA = [
  { date: 'Dec 15', amount: 3200 },
  { date: 'Dec 16', amount: 4100 },
  { date: 'Dec 17', amount: 2800 },
  { date: 'Dec 18', amount: 5600 },
  { date: 'Dec 19', amount: 4900 },
  { date: 'Dec 20', amount: 3700 },
  { date: 'Dec 21', amount: 6200 },
];

const MOCK_STATUS_DATA = [
  { name: 'Paid', value: 145, color: '#34d399' },
  { name: 'Outstanding', value: 23, color: '#fbbf24' },
  { name: 'Overdue', value: 5, color: '#f87171' },
  { name: 'Void', value: 8, color: '#64748b' },
];

const MOCK_INVOICES = [
  { id: 'in_1MqJ2K', customer: 'Acme Corp', amount: 1999, currency: 'USD', status: 'paid', due_date: '2024-01-15', paid_at: '2024-01-14' },
  { id: 'in_2NpL3M', customer: 'TechStart Inc', amount: 4500, currency: 'USD', status: 'outstanding', due_date: '2024-01-20', paid_at: null },
  { id: 'in_3OqM4N', customer: 'Global Ltd', amount: 2750, currency: 'USD', status: 'overdue', due_date: '2024-01-05', paid_at: null },
  { id: 'in_4PrN5O', customer: 'StartupXYZ', amount: 999, currency: 'USD', status: 'paid', due_date: '2024-01-18', paid_at: '2024-01-17' },
  { id: 'in_5QsO6P', customer: 'Enterprise Co', amount: 12000, currency: 'USD', status: 'outstanding', due_date: '2024-01-25', paid_at: null },
];

const COLORS = ['#34d399', '#fbbf24', '#f87171', '#64748b'];

const formatCurrency = (amount: number, currency: string = 'USD') => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: 2
  }).format(amount / 100);
};

const formatDate = (timestamp: number | string) => {
  if (!timestamp) return '—';
  const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp * 1000);
  return date.toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' });
};

const getStatusBadgeClass = (status: string) => {
  const classes: Record<string, string> = {
    paid: 'status-paid',
    outstanding: 'status-outstanding',
    overdue: 'status-overdue',
    void: 'status-void',
    draft: 'status-void'
  };
  return classes[status] || 'status-void';
};

const KPICard = ({ label, value, trend, trendValue, count, icon: Icon }: any) => (
  <div className="kpi-card">
    <div className="flex items-center justify-between mb-2">
      <span className="kpi-label">{label}</span>
      {Icon && <Icon className="icon-md text-slate-400" />}
    </div>
    <div className="kpi-value">{value}</div>
    {count !== undefined && (
      <div className="text-xs text-slate-400 mt-1">{count} invoices</div>
    )}
    {trend && (
      <div className={`kpi-trend ${trend === 'up' ? 'trend-up' : 'trend-down'}`}>
        {trend === 'up' ? <TrendingUp size={14} /> : <TrendingDown size={14} />}
        {trendValue > 0 ? '+' : ''}{trendValue}%
      </div>
    )}
  </div>
);

const ConnectPrompt = ({ onConnect }: { onConnect: () => void }) => (
  <div className="connect-prompt">
    <div className="glass-elevated p-8 rounded-2xl max-w-md w-full">
      <div className="flex items-center justify-center mb-4">
        <div className="w-12 h-12 rounded-full bg-[#635bff]/20 flex items-center justify-center">
          <CreditCard className="text-[#635bff]" size={24} />
        </div>
      </div>
      <h2 className="text-xl font-semibold text-white mb-2 text-center">Connect Stripe Account</h2>
      <p className="text-slate-400 text-sm mb-6 text-center">
        Link your Stripe account to view invoice analytics, payment insights, and revenue metrics in real-time.
      </p>
      <button onClick={onConnect} className="connect-btn w-full justify-center">
        <Link size={18} />
        Connect with Stripe
      </button>
      <div className="mt-6 pt-6 border-t border-white/[0.08]">
        <p className="text-xs text-slate-500 text-center mb-3">Preview of what you'll see:</p>
        <div className="connect-preview rounded-lg overflow-hidden">
          <div className="p-3 space-y-2">
            <div className="flex gap-2">
              <div className="h-16 bg-white/[0.05] rounded flex-1" />
              <div className="h-16 bg-white/[0.05] rounded flex-1" />
            </div>
            <div className="h-24 bg-white/[0.05] rounded" />
          </div>
        </div>
      </div>
    </div>
  </div>
);

export default function App() {
  const [connected, setConnected] = useState(false);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortColumn, setSortColumn] = useState('due_date');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
  const [currentPage, setCurrentPage] = useState(1);
  const [lastSynced, setLastSynced] = useState<Date | null>(null);

  // Simulate connection check on mount
  useEffect(() => {
    // In production, this would check /api/framework/connections/app/fintech-invoice-dashboard/data
    // For now, show disconnected state (credentials not yet added)
    setConnected(false);
  }, []);

  const handleConnect = useCallback(() => {
    // In production, this triggers OAuth flow via dispatch('oauth', { service: 'stripe' })
    // or navigates to the connection endpoint
    alert('In production, this would open Stripe OAuth flow. For now, credentials must be added via: agentsmon-cli vault set stripe:sandbox "sk_test_..."');
  }, []);

  const handleRefresh = useCallback(() => {
    setLoading(true);
    setTimeout(() => {
      setLastSynced(new Date());
      setLoading(false);
    }, 1000);
  }, []);

  const filteredInvoices = MOCK_INVOICES.filter(inv =>
    inv.customer.toLowerCase().includes(searchTerm.toLowerCase()) ||
    inv.id.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const sortedInvoices = [...filteredInvoices].sort((a, b) => {
    const aVal = a[sortColumn as keyof typeof a];
    const bVal = b[sortColumn as keyof typeof b];
    if (aVal === null) return 1;
    if (bVal === null) return -1;
    const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
    return sortDirection === 'asc' ? cmp : -cmp;
  });

  const handleSort = (column: string) => {
    if (sortColumn === column) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortColumn(column);
      setSortDirection('asc');
    }
  };

  if (!connected) {
    return (
      <div className="min-h-screen bg-[#0a0e1a]">
        <header className="header">
          <div className="header-brand">
            <div className="w-8 h-8 rounded-lg bg-[#635bff]/20 flex items-center justify-center">
              <CreditCard className="text-[#635bff]" size={18} />
            </div>
            <div>
              <h1 className="header-title">Invoice Analytics</h1>
              <p className="header-subtitle">Stripe Dashboard</p>
            </div>
          </div>
        </header>
        <ConnectPrompt onConnect={handleConnect} />
        <footer className="footer">
          <span>Data from Stripe API</span>
          <span>© 2024 Invoice Analytics</span>
        </footer>
      </div>
    );
  }

  return (
    <div className={`min-h-screen bg-[#0a0e1a] ${loading ? 'loading' : ''}`}>
      {/* Header */}
      <header className="header">
        <div className="header-brand">
          <div className="w-8 h-8 rounded-lg bg-[#635bff]/20 flex items-center justify-center">
            <CreditCard className="text-[#635bff]" size={18} />
          </div>
          <div>
            <h1 className="header-title">Invoice Analytics</h1>
            <p className="header-subtitle">Stripe Dashboard</p>
          </div>
        </div>
        <div className="header-actions">
          <button onClick={handleRefresh} className="btn btn-outline" disabled={loading}>
            <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
            Refresh
          </button>
          <button className="btn btn-outline">
            <Activity size={16} />
            Settings
          </button>
        </div>
      </header>

      {/* KPI Row */}
      <div className="kpi-row">
        <KPICard
          label="Total Revenue"
          value={formatCurrency(MOCK_KPIs.total_revenue.value)}
          trend={MOCK_KPIs.total_revenue.trend}
          trendValue={MOCK_KPIs.total_revenue.trendValue}
          icon={DollarSign}
        />
        <KPICard
          label="Outstanding"
          value={formatCurrency(MOCK_KPIs.outstanding_amount.value)}
          count={MOCK_KPIs.outstanding_amount.count}
          icon={Clock}
        />
        <KPICard
          label="Overdue"
          value={formatCurrency(MOCK_KPIs.overdue_amount.value)}
          count={MOCK_KPIs.overdue_amount.count}
          icon={AlertCircle}
        />
        <KPICard
          label="Paid This Month"
          value={formatCurrency(MOCK_KPIs.paid_this_month.value)}
          trend={MOCK_KPIs.paid_this_month.trend}
          trendValue={MOCK_KPIs.paid_this_month.trendValue}
          icon={CheckCircle}
        />
      </div>

      {/* Charts Grid */}
      <div className="charts-grid">
        <div className="chart-card">
          <div className="chart-title">
            <Activity size={18} className="text-[#3b82f6]" />
            Revenue Over Time
          </div>
          <ResponsiveContainer width="100%" height={250}>
            <AreaChart data={MOCK_REVENUE_DATA}>
              <defs>
                <linearGradient id="colorAmount" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="date" stroke="#64748b" fontSize={12} />
              <YAxis stroke="#64748b" fontSize={12} tickFormatter={(v) => `$${v}`} />
              <Tooltip
                contentStyle={{ backgroundColor: 'rgba(15,23,42,0.95)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                labelStyle={{ color: '#94a3b8' }}
                formatter={(v: number) => [`$${v}`, 'Revenue']}
              />
              <Area type="monotone" dataKey="amount" stroke="#3b82f6" fillOpacity={1} fill="url(#colorAmount)" />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        <div className="chart-card">
          <div className="chart-title">
            <FileText size={18} className="text-[#3b82f6]" />
            Payment Status Distribution
          </div>
          <ResponsiveContainer width="100%" height={250}>
            <PieChart>
              <Pie
                data={MOCK_STATUS_DATA}
                cx="50%"
                cy="50%"
                innerRadius={60}
                outerRadius={80}
                paddingAngle={2}
                dataKey="value"
              >
                {MOCK_STATUS_DATA.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip
                contentStyle={{ backgroundColor: 'rgba(15,23,42,0.95)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
              />
              <Legend wrapperStyle={{ fontSize: '12px', marginTop: '10px' }} />
            </PieChart>
          </ResponsiveContainer>
          <div className="flex justify-center gap-4 mt-2 text-xs">
            {MOCK_STATUS_DATA.map((item) => (
              <div key={item.name} className="flex items-center gap-1">
                <div className="w-2 h-2 rounded-full" style={{ backgroundColor: item.color }} />
                <span className="text-slate-400">{item.name}: {item.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Invoice Table */}
      <div className="table-container">
        <div className="table-controls">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
            <input
              type="text"
              placeholder="Search invoices..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="search-input pl-10"
            />
          </div>
        </div>
        <div className="glass rounded-xl overflow-hidden">
          <table className="data-table">
            <thead>
              <tr>
                <th onClick={() => handleSort('id')} className="cursor-pointer">
                  Invoice ID {sortColumn === 'id' && (sortDirection === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('customer')} className="cursor-pointer">
                  Customer {sortColumn === 'customer' && (sortDirection === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('amount')} className="cursor-pointer text-right">
                  Amount {sortColumn === 'amount' && (sortDirection === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('status')} className="cursor-pointer">
                  Status {sortColumn === 'status' && (sortDirection === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('due_date')} className="cursor-pointer">
                  Due Date {sortColumn === 'due_date' && (sortDirection === 'asc' ? '↑' : '↓')}
                </th>
                <th>Paid Date</th>
              </tr>
            </thead>
            <tbody>
              {sortedInvoices.map((invoice) => (
                <tr key={invoice.id} className="cursor-pointer hover:bg-white/[0.02]">
                  <td>
                    <span className="invoice-id font-mono text-sm">{invoice.id}</span>
                  </td>
                  <td className="text-slate-300">{invoice.customer}</td>
                  <td className="amount font-semibold">{formatCurrency(invoice.amount, invoice.currency)}</td>
                  <td>
                    <span className={`status-badge ${getStatusBadgeClass(invoice.status)}`}>
                      {invoice.status === 'paid' && <CheckCircle size={12} />}
                      {invoice.status === 'outstanding' && <Clock size={12} />}
                      {invoice.status === 'overdue' && <AlertCircle size={12} />}
                      {invoice.status}
                    </span>
                  </td>
                  <td className="text-slate-300">{formatDate(invoice.due_date)}</td>
                  <td className="text-slate-400">{formatDate(invoice.paid_at)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="pagination">
          <div className="pagination-info">
            Showing {sortedInvoices.length} of {MOCK_INVOICES.length} invoices
          </div>
          <div className="pagination-controls">
            <button
              onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
              disabled={currentPage === 1}
              className="page-btn disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <button className="page-btn active">1</button>
            <button className="page-btn">2</button>
            <button className="page-btn">3</button>
            <button
              onClick={() => setCurrentPage(Math.min(3, currentPage + 1))}
              disabled={currentPage === 3}
              className="page-btn disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className="footer">
        <span>Last synced: {lastSynced ? lastSynced.toLocaleString() : 'Never'}</span>
        <span>Data from Stripe API • UTC Timezone</span>
      </footer>
    </div>
  );
}
