import { useEffect, useState } from 'react';
import api from '../../store/api';
import { useAuthStore } from '../../store/auth';
import { Loader2, AlertCircle, RefreshCw, Receipt, Bus, Tag, ChevronDown, ChevronUp } from 'lucide-react';
import { PayFeesModal, PaymentHistory } from '../../components/PaynowPayment';

interface FeeRow {
  id: number;
  amount: number;
  discount_amount: number;
  paid_amount: number;
  status: 'pending' | 'partial' | 'paid' | 'cancelled';
  due_date: string | null;
  fee_name: string | null;
  fee_type: string | null;
  plan_name: string | null;
  discounts: Array<{ discount_name: string; discount_kind: 'percent' | 'fixed'; amount_applied: number }>;
}
interface TripRow {
  id: number;
  trip_name: string;
  departure_date: string | null;
  invoiced_amount: number;
  paid_amount: number;
  status: string;
}
interface Profile {
  student: { first_name: string; last_name: string; email: string };
  fees: FeeRow[];
  trips: TripRow[];
  summary: {
    fees_count: number;
    overdue_count: number;
    outstanding: number;
    total_discount: number;
    trips_count: number;
    trips_outstanding: number;
  };
}

const currency = (n: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(Number.isFinite(n) ? n : 0);

const statusColor = (s: string) => {
  const v = s.toLowerCase();
  if (v === 'paid') return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300';
  if (v === 'partial' || v === 'issued') return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
  if (v === 'refunded' || v === 'cancelled') return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300';
  return 'bg-muted text-text-muted border-border';
};

export default function StudentFees() {
  const { user } = useAuthStore();
  const [profile, setProfile] = useState<Profile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showPay, setShowPay] = useState<null | { studentId: number }>(null);
  const [showDiscountsFor, setShowDiscountsFor] = useState<number | null>(null);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await api.get('/students/me/fees');
      setProfile(res.data);
    } catch (e: any) {
      setError(e?.response?.data?.error || e?.message || 'Failed to load fees');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user?.id) load();
  }, [user?.id]);

  if (loading) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <Loader2 className="animate-spin" size={32} />
        <p>Loading your fees…</p>
      </div>
    );
  }

  if (error || !profile) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <AlertCircle size={32} className="text-rose-500" />
        <p>{error || 'No data.'}</p>
        <button onClick={load} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl">
          <RefreshCw size={14} /> Retry
        </button>
      </div>
    );
  }

  const fees = profile.fees || [];
  const trips = profile.trips || [];
  const summary = profile.summary;

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">My Fees</h1>
          <p className="text-text-muted mt-1 text-lg">
            {profile.student.first_name} {profile.student.last_name} · billed fees &amp; trip bills.
          </p>
        </div>
        <button
          onClick={() => setShowPay({ studentId: profile.student.id || (user as any).id })}
          disabled={summary.outstanding <= 0 && summary.trips_outstanding <= 0}
          className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98] disabled:opacity-40"
        >
          <Receipt size={18} />
          <span>Pay outstanding</span>
        </button>
      </div>

      {/* Summary tiles */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Tile label="Fees" value={summary.fees_count} tone="blue" />
        <Tile label="Outstanding" value={currency(summary.outstanding)} tone="orange" />
        <Tile label="Discounts applied" value={currency(summary.total_discount)} tone="emerald" />
        <Tile label="Overdue" value={summary.overdue_count} tone={summary.overdue_count > 0 ? 'rose' : 'emerald'} />
      </div>

      {/* Fees table */}
      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="px-6 py-4 border-b border-border bg-muted/30">
          <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Fee lines</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/50">
              <tr>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Fee</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Due</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Amount</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Discount</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Outstanding</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {fees.length > 0 ? (
                fees.map((f) => {
                  const net = (Number(f.amount) || 0) - (Number(f.discount_amount) || 0);
                  const outstanding = Math.max(0, net - (Number(f.paid_amount) || 0));
                  const showDiscounts = showDiscountsFor === f.id;
                  return (
                    <FeeRowComponent
                      key={f.id}
                      fee={f}
                      outstanding={outstanding}
                      net={net}
                      showDiscounts={showDiscounts}
                      onToggleDiscounts={() => setShowDiscountsFor(showDiscounts ? null : f.id)}
                    />
                  );
                })
              ) : (
                <tr><td colSpan={7} className="px-6 py-10 text-center text-text-muted text-sm">No fees on record yet.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Trips */}
      {trips.length > 0 && (
        <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
          <div className="px-6 py-4 border-b border-border bg-muted/30">
            <h3 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary flex items-center gap-2"><Bus size={14} /> Trip bills</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead className="bg-muted/50">
                <tr>
                  <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Trip</th>
                  <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Departure</th>
                  <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Invoiced</th>
                  <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Paid</th>
                  <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Outstanding</th>
                  <th className="px-6 py-3 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {trips.map((t) => {
                  const outstanding = Math.max(0, (Number(t.invoiced_amount) || 0) - (Number(t.paid_amount) || 0));
                  return (
                    <tr key={t.id} className="hover:bg-muted/40 transition-colors">
                      <td className="px-6 py-3 text-[0.85rem] font-semibold text-text">{t.trip_name}</td>
                      <td className="px-6 py-3 text-[0.75rem] font-mono text-text-muted">{t.departure_date || '—'}</td>
                      <td className="px-6 py-3 text-right text-[0.85rem] font-mono">{currency(Number(t.invoiced_amount))}</td>
                      <td className="px-6 py-3 text-right text-[0.85rem] font-mono text-emerald-600">{currency(Number(t.paid_amount))}</td>
                      <td className="px-6 py-3 text-right text-[0.85rem] font-bold text-rose-500">{currency(outstanding)}</td>
                      <td className="px-6 py-3">
                        <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusColor(t.status)}`}>{t.status}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <PaymentHistory studentId={(user as any).id || 0} />

      {showPay && (
        <PayFeesModal
          studentId={showPay.studentId}
          onClose={() => {
            setShowPay(null);
            load();
          }}
        />
      )}
    </div>
  );
}

function FeeRowComponent({
  fee, outstanding, net, showDiscounts, onToggleDiscounts,
}: {
  fee: FeeRow;
  outstanding: number;
  net: number;
  showDiscounts: boolean;
  onToggleDiscounts: () => void;
}) {
  return (
    <>
      <tr className="hover:bg-muted/40 transition-colors">
        <td className="px-6 py-3">
          <p className="text-[0.85rem] font-semibold text-text">{fee.fee_name || 'Fee line'}</p>
          {fee.plan_name && <p className="text-[0.65rem] text-text-muted italic">Plan: {fee.plan_name}</p>}
          {fee.discounts.length > 0 && (
            <button onClick={onToggleDiscounts} className="text-[0.65rem] text-primary font-bold mt-0.5 flex items-center gap-0.5">
              {showDiscounts ? <ChevronUp size={10} /> : <ChevronDown size={10} />} {fee.discounts.length} discount{fee.discounts.length === 1 ? '' : 's'}
            </button>
          )}
        </td>
        <td className="px-6 py-3 text-[0.85rem] font-mono text-text-muted">{fee.due_date?.slice(0, 10) || '—'}</td>
        <td className="px-6 py-3 text-right text-[0.85rem] font-mono">{currency(Number(fee.amount))}</td>
        <td className="px-6 py-3 text-right text-[0.85rem] font-mono text-rose-500">
          {Number(fee.discount_amount) > 0 ? `−${currency(Number(fee.discount_amount))}` : '—'}
        </td>
        <td className="px-6 py-3 text-right text-[0.85rem] font-bold">{currency(outstanding)}</td>
        <td className="px-6 py-3">
          <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusColor(fee.status)}`}>{fee.status}</span>
        </td>
        <td className="px-6 py-3 text-right" />
      </tr>
      {showDiscounts && (
        <tr className="bg-muted/30">
          <td colSpan={7} className="px-6 py-3">
            <div className="flex flex-wrap gap-2 text-xs">
              {fee.discounts.map((d, i) => (
                <span key={i} className="flex items-center gap-1 px-2.5 py-1 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-700">
                  <Tag size={10} /> {d.discount_name} {d.discount_kind === 'percent' ? `−${d.amount_applied}` : `−$${d.amount_applied.toFixed(2)}`}
                </span>
              ))}
            </div>
          </td>
        </tr>
      )}
    </>
  );
}

function Tile({ label, value, tone }: { label: string; value: string | number; tone?: 'emerald' | 'orange' | 'rose' | 'blue' }) {
  const colorCls = tone === 'emerald' ? 'text-emerald-600' : tone === 'orange' ? 'text-orange-600' : tone === 'rose' ? 'text-rose-600' : tone === 'blue' ? 'text-blue-600' : 'text-text';
  return (
    <div className="bg-card border border-border rounded-2xl p-4 shadow-sm">
      <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
      <p className={`text-2xl font-black mt-1 ${colorCls}`}>{value}</p>
    </div>
  );
}
