import { useState } from 'react';
import { useFeeStore } from '@/stores/feeStore';
import { useUIStore } from '@/stores/uiStore';
import { useStudentStore } from '@/stores/studentStore';
import { StatsCard, StatusBadge, SectionTitle, WhatsAppButton } from '@/components/common';
import { formatCurrency, formatDate } from '@/lib/formatters';
import { IndianRupee, AlertCircle, TrendingUp, Receipt, ChevronRight, MessageCircle } from 'lucide-react';

export default function FeeDashboardScreen() {
  const { receipts, dueList } = useFeeStore();
  const { students } = useStudentStore();
  const { navigateTo } = useUIStore();

  const totalCollected = receipts.reduce((s, r) => s + r.amountPaid, 0);
  const totalDue = dueList.reduce((s, d) => s + d.amount, 0);
  const collectionRate = receipts.length > 0 ? Math.round((receipts.filter(r => r.status === 'paid').length / (receipts.length + dueList.length)) * 100) : 0;

  return (
    <div className="px-4 pt-4 pb-4 space-y-5">
      {/* Summary Stats */}
      <div className="grid grid-cols-3 gap-3">
        <StatsCard icon={<IndianRupee className="w-5 h-5 text-emerald-500" />} label="Collected" value={formatCurrency(totalCollected).replace('\u20b9', '')} subtitle="this month" trend="8%" trendUp />
        <StatsCard icon={<AlertCircle className="w-5 h-5 text-red-500" />} label="Total Due" value={formatCurrency(totalDue).replace('\u20b9', '')} subtitle={`${dueList.length} students`} />
        <StatsCard icon={<TrendingUp className="w-5 h-5 text-orange-500" />} label="Collection" value={`${collectionRate}%`} subtitle="rate" />
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-2 gap-3">
        <button onClick={() => navigateTo('recordPayment')} className="h-12 brand-gradient text-white font-semibold rounded-xl button-shadow text-sm active:scale-[0.98] transition-transform flex items-center justify-center gap-2">
          <Receipt className="w-4 h-4" /> Record Payment
        </button>
        <button onClick={() => navigateTo('dueFees')} className="h-12 border border-orange-500 text-orange-500 font-semibold rounded-xl text-sm active:scale-[0.98] transition-transform flex items-center justify-center gap-2">
          <AlertCircle className="w-4 h-4" /> View Due List
        </button>
      </div>

      {/* Due Fees */}
      {dueList.length > 0 && (
        <div>
          <SectionTitle title="Due Fees" action={<span className="text-[10px] bg-red-500 text-white px-2 py-0.5 rounded-full font-medium">{dueList.length}</span>} />
          <div className="space-y-2">
            {dueList.slice(0, 5).map(d => (
              <div key={d.studentId} className="bg-white rounded-xl p-4 card-shadow border-l-4 border-red-500">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-semibold text-gray-900">{d.studentName}</p>
                    <p className="text-[10px] text-gray-400">{d.studentIdCode} &bull; {d.batchName}</p>
                    <p className="text-[10px] text-red-500 mt-0.5">{d.daysOverdue} days overdue</p>
                  </div>
                  <p className="text-base font-bold text-red-600">{formatCurrency(d.amount)}</p>
                </div>
                {/* WhatsApp Reminder */}
                <a href={`https://wa.me/${d.phone}?text=${encodeURIComponent(`Dear Parent,\n\nThis is a gentle reminder that the skating academy fee of ${formatCurrency(d.amount)} for ${d.studentName} (${d.studentIdCode}) is overdue by ${d.daysOverdue} days.\n\nKindly pay the fees at the earliest.\n\nThank you,\nSkatePro Academy`)}`}
                  target="_blank" rel="noopener noreferrer"
                  className="mt-3 flex items-center justify-center gap-2 w-full py-2.5 bg-[#25D366] text-white text-xs font-bold rounded-xl active:scale-[0.97] transition-transform">
                  <MessageCircle className="w-4 h-4" /> Send Fee Reminder on WhatsApp
                </a>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Recent Receipts */}
      <div>
        <SectionTitle title="Recent Receipts" />
        <div className="space-y-2">
          {receipts.slice(0, 5).map(r => (
            <div key={r.id} className="bg-white rounded-xl p-4 card-shadow">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Receipt className="w-4 h-4 text-orange-500" />
                  <span className="text-xs font-mono text-gray-500">{r.receiptNumber}</span>
                </div>
                <StatusBadge status="paid" />
              </div>
              <div className="flex items-center justify-between mt-2">
                <div>
                  <p className="text-sm font-semibold text-gray-900">{r.studentName}</p>
                  <p className="text-[10px] text-gray-400">{formatDate(r.paymentDate)}</p>
                </div>
                <div className="text-right">
                  <p className="text-base font-bold text-gray-900">{formatCurrency(r.amountPaid)}</p>
                  <p className="text-[10px] text-gray-400 capitalize">{r.paymentMethod}</p>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
