import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
 FileText, FileCheck, TrendingUp, Clock, CheckCircle, Users,
 Plus, ArrowRight, MessageCircle, Calendar, ShieldCheck
} from 'lucide-react'
import useAuthStore from '@/context/authStore'
import { getInvoiceSummary, getInvoices } from '@/services/invoiceService'
import { getQuotations } from '@/services/quotationService'
import { getClients } from '@/services/clientService'
import { formatCurrency } from '@/utils/numberFormat'
import { formatDate } from '@/utils/dateUtils'
import { Button } from '@/components/ui/Button'
import { Badge } from '@/components/ui/Badge'
import { SkeletonCard } from '@/components/ui/Skeleton'
import PrivacyText from '@/components/PrivacyText'
import MiniChart from '@/components/ui/MiniChart'

function StatCard({ label, value, icon: Icon, color, chartData, trend }) {
  return (
    <div className="rounded-2xl border border-surface-800 bg-surface-900/50 backdrop-blur-sm p-3 lg:p-4 hover:border-surface-700 transition-all duration-300 hover:shadow-2xl hover:shadow-primary-500/5 group animate-slide-up relative overflow-hidden">
      <div className="absolute top-0 right-0 w-24 h-24 -mt-8 -mr-8 bg-current opacity-[0.03] rounded-full blur-2xl pointer-events-none" style={{ color: color.includes('emerald') ? '#10b981' : color.includes('primary') ? '#7c3aed' : '#f59e0b' }} />
      
      <div className="flex items-center justify-between mb-3">
        <div className={`p-2 rounded-xl ${color} bg-opacity-10 ring-1 ring-inset ring-white/10 flex items-center justify-center shadow-inner`}>
          <Icon size={18} className="text-white" />
        </div>
        {trend && (
          <div className="flex items-center gap-1 text-[10px] font-black text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-md border border-emerald-500/20 uppercase tracking-tighter">
            <TrendingUp size={10} />
            {trend}
          </div>
        )}
      </div>
      
      <div className="space-y-0.5">
        <h4 className="text-[10px] font-black text-surface-500 uppercase tracking-widest">{label}</h4>
        <p className="text-lg lg:text-2xl font-black text-surface-50 tracking-tight leading-none pt-1">
          <PrivacyText>{value}</PrivacyText>
        </p>
      </div>
      
      {chartData && (
        <div className="mt-4 h-10 opacity-30 group-hover:opacity-100 transition-opacity">
          <MiniChart data={chartData} color={color.includes('emerald') ? '#10b981' : color.includes('amber') ? '#f59e0b' : '#8b5cf6'} height={40} />
        </div>
      )}
    </div>
  )
}

function QuickActionCard({ title, icon: Icon, onClick, gradient, subtitle }) {
  return (
    <button
      onClick={onClick}
      className={`w-full rounded-2xl p-4 text-left transition-all duration-300 
      hover:-translate-y-1 active:scale-95 ${gradient} text-white group relative overflow-hidden shadow-xl shadow-black/20`}
    >
      <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:scale-125 transition-transform">
        <Icon size={48} strokeWidth={3} />
      </div>
      <div className="relative z-10 flex flex-col h-full justify-between">
        <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-md border border-white/20 group-hover:rotate-12 transition-transform shadow-lg">
          <Icon size={20} strokeWidth={2.5} />
        </div>
        <div className="mt-4">
          <h3 className="text-sm font-black leading-tight tracking-tight uppercase">{title}</h3>
          {subtitle && (
            <p className="text-[10px] font-bold text-white/70 mt-0.5 tracking-wide">{subtitle}</p>
          )}
        </div>
      </div>
    </button>
  )
}

import useDashboardStore from '@/context/dashboardStore'

export default function DashboardPage() {
 const { companyId } = useAuthStore()
 const navigate = useNavigate()
 const { 
   summary, totalClients, totalQuotations, recentInvoices, 
   setDashboardData 
 } = useDashboardStore()
 
 // Only block with full skeletons if we have ZERO data
 const [pageLoading, setPageLoading] = useState(!summary)

 useEffect(() => {
   if (!companyId) return
   
   const load = async () => {
     try {
       const [sumData, clients, quotations, invoices] = await Promise.all([
         getInvoiceSummary(companyId),
         getClients(companyId),
         getQuotations(companyId),
         getInvoices(companyId),
       ])
       
       setDashboardData({
         summary: sumData,
         totalClients: clients.length,
         totalQuotations: quotations.length,
         recentInvoices: invoices.slice(0, 5)
       })
     } catch (err) {
       console.error('Dashboard load error:', err)
     } finally {
       setPageLoading(false)
     }
   }
   
   load()
 }, [companyId, setDashboardData])

 const displayLoading = pageLoading && !summary

  return (
    <div className="p-2 lg:p-3 space-y-3 lg:space-y-4 animate-fade-in">
      {/* Page Header - Quick Overview */}
      <div className="flex items-end justify-between lg:mb-2">
        <div>
          <h2 className="text-[10px] font-black text-primary-400 uppercase tracking-[0.25em] mb-1 px-1">Command Center</h2>
          <h1 className="text-xl lg:text-3xl font-black text-surface-50 tracking-tight flex items-center gap-2">
            Overview <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse shadow-[0_0_8px_rgba(16,185,129,0.8)]" />
          </h1>
        </div>
        <p className="hidden lg:block text-xs font-bold text-surface-500">
          Last active: <span className="text-surface-300">{formatDate(new Date())}</span>
        </p>
      </div>

      {/* Quick Actions Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 lg:gap-5">
        <QuickActionCard
          title="Create Bill"
          subtitle="New Sales Invoice"
          icon={Plus}
          onClick={() => navigate('/invoices/new')}
          gradient="bg-gradient-brand shadow-primary-500/20"
        />
        <QuickActionCard
          title="New Quote"
          subtitle="Pro-forma / Estimate"
          icon={FileCheck}
          onClick={() => navigate('/quotations/new')}
          gradient="bg-gradient-to-br from-blue-600 to-indigo-700 shadow-blue-500/20"
        />
        <QuickActionCard
          title="Add Client"
          subtitle="Customer Directory"
          icon={Users}
          onClick={() => navigate('/clients/new')}
          gradient="bg-gradient-to-br from-slate-700 to-slate-900 border border-surface-700 shadow-surface-500/10"
        />
        <QuickActionCard
          title="GST Report"
          subtitle="Purchase vs Sales"
          icon={TrendingUp}
          onClick={() => navigate('/reports/gst')}
          gradient="bg-gradient-to-br from-emerald-600 to-teal-800 shadow-emerald-500/20"
        />
      </div>

 {/* Stats Grid */}
 <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
 {displayLoading ? (
 Array.from({ length: 4 }).map((_, i) => <SkeletonCard key={i} />)
 ) : (
 <>
  <StatCard
    label="Total Sales"
    value={formatCurrency(summary?.totalSales ?? 0)}
    icon={TrendingUp}
    color="bg-gradient-to-br from-primary-600 to-primary-700"
    chartData={[40, 60, 45, 70, 65, 85, 100]}
    trend={summary?.totalInvoices ? `${summary.totalInvoices} bills` : null}
  />
  <StatCard
    label="Paid Amount"
    value={formatCurrency(summary?.paidAmount ?? 0)}
    icon={CheckCircle}
    color="bg-gradient-to-br from-emerald-600 to-emerald-700"
    chartData={[30, 40, 35, 50, 48, 60, 75]}
    trend={summary?.totalSales > 0 ? `${Math.round((summary.paidAmount / summary.totalSales) * 100)}%` : null}
  />
  <StatCard
    label="Pending Amount"
    value={formatCurrency(summary?.pendingAmount ?? 0)}
    icon={Clock}
    color="bg-gradient-to-br from-amber-600 to-orange-600"
    chartData={[20, 15, 25, 18, 22, 10, 5]}
    trend={summary?.totalSales > 0 ? `${Math.round((summary.pendingAmount / summary.totalSales) * 100)}%` : null}
  />
  <StatCard
     label="Total GST"
     value={formatCurrency(summary?.totalGST ?? 0)}
     icon={FileText}
     color="bg-gradient-to-br from-purple-600 to-indigo-700"
     chartData={[10, 15, 12, 20, 18, 25, 30]}
   />
 </>
 )}
 </div>

  {/* Summary Row */}
      {/* Secondary Stats Row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 lg:gap-6">
        <div
          className="rounded-2xl border border-surface-800 bg-surface-900/40 p-3 flex flex-col lg:flex-row items-center gap-3 cursor-pointer hover:border-primary-500/50 hover:bg-surface-800/50 transition-all text-center lg:text-left group"
          onClick={() => navigate('/clients')}
        >
          <div className="p-2 rounded-xl bg-blue-500/10 group-hover:scale-110 transition-transform">
            <Users size={16} className="text-blue-400" />
          </div>
          <div className="min-w-0">
            <p className="text-lg lg:text-xl font-black text-surface-100 leading-none">{displayLoading ? '—' : totalClients}</p>
            <p className="text-[9px] font-black text-surface-500 uppercase mt-1 tracking-widest truncate">Total Clients</p>
          </div>
        </div>

        <div
          className="rounded-2xl border border-surface-800 bg-surface-900/40 p-3 flex flex-col lg:flex-row items-center gap-3 cursor-pointer hover:border-primary-500/50 hover:bg-surface-800/50 transition-all text-center lg:text-left group"
          onClick={() => navigate('/invoices')}
        >
          <div className="p-2 rounded-xl bg-primary-500/10 group-hover:scale-110 transition-transform">
            <FileText size={16} className="text-primary-400" />
          </div>
          <div className="min-w-0">
            <p className="text-lg lg:text-xl font-black text-surface-100 leading-none">{displayLoading ? '—' : summary?.totalInvoices ?? 0}</p>
            <p className="text-[9px] font-black text-surface-500 uppercase mt-1 tracking-widest truncate">Active Bills</p>
            {!displayLoading && summary && (
              <div className="flex items-center gap-1.5 mt-1.5 flex-wrap justify-center lg:justify-start">
                {summary.paidCount > 0 && <span className="text-[8px] font-black text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded-md">{summary.paidCount} Paid</span>}
                {summary.partialCount > 0 && <span className="text-[8px] font-black text-amber-400 bg-amber-500/10 px-1.5 py-0.5 rounded-md">{summary.partialCount} Partial</span>}
                {summary.unpaidCount > 0 && <span className="text-[8px] font-black text-red-400 bg-red-500/10 px-1.5 py-0.5 rounded-md">{summary.unpaidCount} Unpaid</span>}
                {summary.discountedCount > 0 && <span className="text-[8px] font-black text-indigo-400 bg-indigo-500/10 px-1.5 py-0.5 rounded-md">{summary.discountedCount} Discounted</span>}
              </div>
            )}
          </div>
        </div>

        <div
          className="rounded-2xl border border-surface-800 bg-surface-900/40 p-3 flex flex-col lg:flex-row items-center gap-3 cursor-pointer hover:border-primary-500/50 hover:bg-surface-800/50 transition-all text-center lg:text-left group"
          onClick={() => navigate('/quotations')}
        >
          <div className="p-2 rounded-xl bg-blue-500/10 group-hover:scale-110 transition-transform">
            <FileCheck size={16} className="text-blue-400" />
          </div>
          <div className="min-w-0">
            <p className="text-lg lg:text-xl font-black text-surface-100 leading-none">{displayLoading ? '—' : totalQuotations}</p>
            <p className="text-[9px] font-black text-surface-500 uppercase mt-1 tracking-widest truncate">Open Quotes</p>
          </div>
        </div>

        <div
          className="rounded-2xl border border-surface-800 bg-surface-900/40 p-3 flex flex-col lg:flex-row items-center gap-3 cursor-pointer hover:border-emerald-500/50 hover:bg-surface-800/50 transition-all text-center lg:text-left group"
          onClick={() => navigate('/invoices')}
        >
          <div className="p-2 rounded-xl bg-emerald-500/10 group-hover:scale-110 transition-transform">
            <ShieldCheck size={16} className="text-emerald-400" />
          </div>
          <div className="min-w-0">
            <p className="text-lg lg:text-xl font-black text-surface-100 leading-none">{displayLoading ? '—' : summary?.paymentProofCount ?? 0}</p>
            <p className="text-[9px] font-black text-surface-500 uppercase mt-1 tracking-widest truncate">Proof Received</p>
            {!displayLoading && summary && summary.paymentProofCount > 0 && (
              <p className="text-[8px] font-black text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded-md mt-1.5 inline-block">
                {Math.round((summary.paymentProofCount / summary.totalInvoices) * 100)}% verified
              </p>
            )}
          </div>
        </div>
      </div>

 {/* Recent Invoices - Excel Style Table */}
 <div className="rounded-2xl border border-surface-800 bg-surface-900 overflow-hidden">
   <div className="px-4 py-3 border-b border-surface-800 flex items-center justify-between">
     <h2 className="text-xs font-semibold text-surface-50 flex items-center gap-2">
       <Calendar size={14} className="text-primary-400" />
       Recent Invoices
     </h2>
     <button onClick={() => navigate('/invoices')} className="text-[10px] text-primary-400 hover:text-primary-300 transition-colors">
       View all →
     </button>
   </div>
   {displayLoading ? (
     <div className="p-4 space-y-3">
       {Array.from({ length: 3 }).map((_, i) => (
         <div key={i} className="h-12 rounded-xl bg-surface-800 animate-pulse" />
       ))}
     </div>
   ) : recentInvoices.length === 0 ? (
     <div className="p-8 text-center">
       <FileText size={32} className="text-surface-600 mx-auto mb-2" />
       <p className="text-surface-400 text-sm">No invoices yet</p>
       <Button size="sm" className="mt-3" onClick={() => navigate('/invoices/new')} icon={<Plus size={14} />}>
         Create First Invoice
       </Button>
     </div>
   ) : (
     <div className="overflow-x-auto">
       <table className="w-full text-sm border-collapse">
         {/* Table Header */}
         <thead>
           <tr className="border-b border-surface-700 bg-surface-950">
             <th className="px-2 py-2 text-left text-[9px] font-black text-surface-500 uppercase tracking-wider border-r border-surface-800 whitespace-nowrap">Invoice #</th>
             <th className="px-2 py-2 text-left text-[9px] font-black text-surface-500 uppercase tracking-wider border-r border-surface-800">Client</th>
             <th className="hidden sm:table-cell px-2 py-2 text-left text-[9px] font-black text-surface-500 uppercase tracking-wider border-r border-surface-800">Services</th>
             <th className="hidden md:table-cell px-2 py-2 text-center text-[9px] font-black text-surface-500 uppercase tracking-wider border-r border-surface-800">Last Payment</th>
             <th className="px-2 py-2 text-right text-[9px] font-black text-surface-500 uppercase tracking-wider border-r border-surface-800">Amount</th>
             <th className="px-2 py-2 text-center text-[9px] font-black text-surface-500 uppercase tracking-wider">Status</th>
           </tr>
         </thead>
         <tbody>
           {recentInvoices.map((inv, idx) => {
             const total = Number(inv.total) || 0
             const paid = Number(inv.paidAmount) || 0
             const isPaid = inv.status === 'paid'
             const isPartial = inv.status === 'partial'

             const lastPayment = inv.paymentHistory && inv.paymentHistory.length > 0
               ? inv.paymentHistory[inv.paymentHistory.length - 1]
               : null;

             const services = (inv.items || []).slice(0, 2).map(item => item.description || item.name).join(', ')

             return (
               <tr
                 key={inv.id}
                 onClick={() => navigate(`/invoices/${inv.id}`)}
                 className="border-b border-surface-800 hover:bg-surface-800/30 cursor-pointer transition-colors"
                 style={{ backgroundColor: idx % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.02)' }}
               >
                 {/* Invoice Number */}
                 <td className="px-2 py-2 border-r border-surface-800/50 whitespace-nowrap">
                   <span className="text-[10px] font-bold text-primary-400">#{inv.invoiceNumber}</span>
                 </td>

                 {/* Client Name */}
                 <td className="px-2 py-2 border-r border-surface-800/50">
                   <p className="text-[10px] font-medium text-surface-50 truncate max-w-[100px] sm:max-w-[150px]">
                     {inv.clientSnapshot?.name || '—'}
                   </p>
                 </td>

                 {/* Services - Hidden on mobile */}
                 <td className="hidden sm:table-cell px-2 py-2 border-r border-surface-800/50">
                   <p className="text-[9px] text-surface-400 truncate max-w-[150px] lg:max-w-[200px]">
                     {services || 'No items'}
                   </p>
                 </td>

                 {/* Last Payment - Hidden on mobile */}
                 <td className="hidden md:table-cell px-2 py-2 text-center border-r border-surface-800/50">
                   {lastPayment ? (
                     <div>
                       <p className="text-[9px] font-bold text-emerald-400">{formatDate(lastPayment.date)}</p>
                       <p className="text-[8px] text-surface-500">{formatCurrency(lastPayment.amount)}</p>
                     </div>
                   ) : (
                     <span className="text-[9px] text-surface-600 italic">—</span>
                   )}
                 </td>

                 {/* Amount */}
                 <td className="px-2 py-2 text-right border-r border-surface-800/50">
                   <p className="text-[10px] font-black text-surface-50">{formatCurrency(total)}</p>
                   {isPartial && (
                     <p className="text-[8px] font-bold text-rose-400">Due: {formatCurrency(total - paid)}</p>
                   )}
                 </td>

                 {/* Status */}
                 <td className="px-1.5 py-2 text-center">
                   <Badge variant={inv.status} className="text-[6px] px-1 py-0 uppercase font-black tracking-tighter min-w-0">
                     {inv.status === 'discounted' ? 'DISC' : inv.status === 'partial' ? 'PART' : inv.status}
                   </Badge>
                 </td>
               </tr>
             )
           })}
         </tbody>
       </table>
     </div>
   )}
 </div>

    </div>
  )
}
