import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Plus, CreditCard, CheckCircle, Trash2, Receipt } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../api/axios';
import Modal from '../components/Modal';
import {
  formatCurrency,
  formatDate,
  statusColors,
  paymentTypeLabels,
  paymentMethodLabels,
} from '../utils/format';

const MONTHS = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December',
];

const emptyPayment = {
  student: '',
  amount: 0,
  paymentType: 'tuition',
  paymentMethod: 'cash',
  status: 'completed',
  term: 'Term 1',
  academicYear: '2025-2026',
  paidAt: new Date().toISOString().slice(0, 10),
  notes: '',
};

export default function StudentPayments() {
  const [searchParams] = useSearchParams();
  const now = new Date();
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [year, setYear] = useState(now.getFullYear());
  const [payments, setPayments] = useState([]);
  const [students, setStudents] = useState([]);
  const [summary, setSummary] = useState(null);
  const [modal, setModal] = useState(false);
  const [form, setForm] = useState(emptyPayment);
  const [loading, setLoading] = useState(true);

  const load = () => {
    setLoading(true);
    Promise.all([
      api.get('/student-payments', { params: { month, year } }),
      api.get('/student-payments/summary', { params: { month, year } }),
      api.get('/students', { params: { status: 'active' } }),
    ])
      .then(([pRes, sRes, stuRes]) => {
        setPayments(pRes.data);
        setSummary(sRes.data);
        setStudents(stuRes.data);
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => { load(); }, [month, year]);

  useEffect(() => {
    const studentId = searchParams.get('student');
    if (studentId && students.length) {
      setForm((f) => ({ ...f, student: studentId }));
      setModal(true);
    }
  }, [searchParams, students]);

  const openCreate = () => {
    setForm({
      ...emptyPayment,
      student: searchParams.get('student') || students[0]?._id || '',
    });
    setModal(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await api.post('/student-payments', form);
      toast.success('Payment recorded');
      setModal(false);
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Error recording payment');
    }
  };

  const markCompleted = async (id) => {
    try {
      await api.patch(`/student-payments/${id}/status`, { status: 'completed' });
      toast.success('Payment completed');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Error');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this payment record?')) return;
    try {
      await api.delete(`/student-payments/${id}`);
      toast.success('Deleted');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Cannot delete');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <h1 className="font-display text-2xl font-bold text-slate-800">Student Payments</h1>
          <p className="text-slate-500">Record tuition and fee payments from students</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <select className="input-field w-auto" value={month} onChange={(e) => setMonth(Number(e.target.value))}>
            {MONTHS.map((m, i) => (
              <option key={m} value={i + 1}>{m}</option>
            ))}
          </select>
          <select className="input-field w-auto" value={year} onChange={(e) => setYear(Number(e.target.value))}>
            {[2024, 2025, 2026, 2027].map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
          <button onClick={openCreate} className="btn-primary">
            <Plus className="h-4 w-4" /> Record Payment
          </button>
        </div>
      </div>

      {summary && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[
            { label: 'Collected This Month', value: formatCurrency(summary.totalCollected), color: 'from-violet-500 to-purple-600' },
            { label: 'Payments', value: summary.paymentCount, color: 'from-emerald-500 to-teal-600' },
            { label: 'Active Students', value: summary.activeStudents, color: 'from-brand-500 to-brand-600' },
            { label: 'Outstanding Fees', value: formatCurrency(summary.totalOutstanding), color: 'from-amber-500 to-orange-500' },
          ].map(({ label, value, color }) => (
            <div key={label} className={`rounded-2xl bg-gradient-to-br ${color} p-5 text-white shadow-lg`}>
              <CreditCard className="mb-2 h-5 w-5 opacity-80" />
              <p className="text-sm text-white/80">{label}</p>
              <p className="font-display text-xl font-bold">{value}</p>
            </div>
          ))}
        </div>
      )}

      <div className="card overflow-hidden p-0">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50">
              <tr className="text-left text-slate-500">
                <th className="px-6 py-4 font-medium">Receipt</th>
                <th className="px-6 py-4 font-medium">Student</th>
                <th className="px-6 py-4 font-medium">Type</th>
                <th className="px-6 py-4 font-medium">Amount</th>
                <th className="px-6 py-4 font-medium">Method</th>
                <th className="px-6 py-4 font-medium">Date</th>
                <th className="px-6 py-4 font-medium">Status</th>
                <th className="px-6 py-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={8} className="px-6 py-12 text-center text-slate-400">Loading...</td></tr>
              ) : payments.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center">
                    <p className="text-slate-400">No payments this period</p>
                    <button onClick={openCreate} className="mt-2 text-violet-600 font-medium hover:underline">
                      Record first payment
                    </button>
                  </td>
                </tr>
              ) : (
                payments.map((p) => (
                  <tr key={p._id} className="border-t border-slate-100 hover:bg-slate-50/50">
                    <td className="px-6 py-4">
                      <span className="flex items-center gap-1.5 font-mono text-xs text-slate-600">
                        <Receipt className="h-3.5 w-3.5" />
                        {p.receiptNumber}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <p className="font-medium text-slate-800">
                        {p.student?.firstName} {p.student?.lastName}
                      </p>
                      <p className="text-xs text-slate-400">
                        {p.student?.studentId} · {p.student?.grade}
                      </p>
                    </td>
                    <td className="px-6 py-4">{paymentTypeLabels[p.paymentType] || p.paymentType}</td>
                    <td className="px-6 py-4 font-bold text-violet-600">{formatCurrency(p.amount)}</td>
                    <td className="px-6 py-4">{paymentMethodLabels[p.paymentMethod] || p.paymentMethod}</td>
                    <td className="px-6 py-4 text-slate-600">{formatDate(p.paidAt)}</td>
                    <td className="px-6 py-4">
                      <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium capitalize ${statusColors[p.status]}`}>
                        {p.status}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex gap-2">
                        {p.status === 'pending' && (
                          <button
                            onClick={() => markCompleted(p._id)}
                            className="rounded-lg p-2 text-emerald-600 hover:bg-emerald-50"
                            title="Mark completed"
                          >
                            <CheckCircle className="h-4 w-4" />
                          </button>
                        )}
                        <button
                          onClick={() => handleDelete(p._id)}
                          className="rounded-lg p-2 text-slate-400 hover:bg-red-50 hover:text-red-600"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title="Record Payment" wide>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <label className="mb-1 block text-sm font-medium">Student</label>
              <select
                className="input-field"
                value={form.student}
                onChange={(e) => setForm({ ...form, student: e.target.value })}
                required
              >
                <option value="">Select student...</option>
                {students.map((s) => (
                  <option key={s._id} value={s._id}>
                    {s.firstName} {s.lastName} ({s.studentId}) — Balance: {formatCurrency(s.balance)}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Amount</label>
              <input
                type="number"
                className="input-field"
                value={form.amount}
                onChange={(e) => setForm({ ...form, amount: Number(e.target.value) })}
                required
                min={1}
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Payment Type</label>
              <select className="input-field" value={form.paymentType} onChange={(e) => setForm({ ...form, paymentType: e.target.value })}>
                {Object.entries(paymentTypeLabels).map(([k, v]) => (
                  <option key={k} value={k}>{v}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Payment Method</label>
              <select className="input-field" value={form.paymentMethod} onChange={(e) => setForm({ ...form, paymentMethod: e.target.value })}>
                {Object.entries(paymentMethodLabels).map(([k, v]) => (
                  <option key={k} value={k}>{v}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Status</label>
              <select className="input-field" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                <option value="completed">Completed</option>
                <option value="pending">Pending</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Payment Date</label>
              <input type="date" className="input-field" value={form.paidAt} onChange={(e) => setForm({ ...form, paidAt: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Term</label>
              <select className="input-field" value={form.term} onChange={(e) => setForm({ ...form, term: e.target.value })}>
                <option>Term 1</option>
                <option>Term 2</option>
                <option>Term 3</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Academic Year</label>
              <input className="input-field" value={form.academicYear} onChange={(e) => setForm({ ...form, academicYear: e.target.value })} />
            </div>
            <div className="sm:col-span-2">
              <label className="mb-1 block text-sm font-medium">Notes</label>
              <textarea className="input-field" rows={2} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
            </div>
          </div>
          <div className="flex justify-end gap-3">
            <button type="button" onClick={() => setModal(false)} className="btn-secondary">Cancel</button>
            <button type="submit" className="btn-primary">Record Payment</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
