import { useState, useEffect } from 'react';
import { CreditCard, Search, CheckCircle2, XCircle, FileText, User, Calendar } from 'lucide-react';
import api from '../../store/auth';

interface LibraryFine {
  id: number;
  uid: string;
  issue_id: number;
  user_id: number;
  amount: number;
  reason: string;
  status: 'unpaid' | 'paid' | 'waived';
  created_at: string;
  book_title: string;
  first_name: string;
  last_name: string;
}

export default function FinesManagement() {
  const [fines, setFines] = useState<LibraryFine[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');

  const fetchFines = async () => {
    try {
      setLoading(true);
      const response = await api.get('/library/fines');
      setFines(response.data);
    } catch (error) {
      console.error('Error fetching fines:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFines();
  }, []);

  const handlePay = async (id: number) => {
    if (!window.confirm('Mark this fine as paid?')) return;
    try {
      await api.post(`/library/fines/${id}/pay`);
      fetchFines();
    } catch (error) {
      alert('Failed to process payment');
    }
  };

  const handleWaive = async (id: number) => {
    if (!window.confirm('Are you sure you want to waive this fine?')) return;
    try {
      await api.post(`/library/fines/${id}/waive`);
      fetchFines();
    } catch (error) {
      alert('Failed to waive fine');
    }
  };

  const filteredFines = fines.filter(f => 
    `${f.first_name} ${f.last_name}`.toLowerCase().includes(search.toLowerCase()) ||
    f.book_title.toLowerCase().includes(search.toLowerCase())
  );

  const totalOutstanding = fines.filter(f => f.status === 'unpaid').reduce((acc, f) => acc + f.amount, 0);

  return (
    <div className="p-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-bold text-text flex items-center gap-2">
            <CreditCard className="text-primary" aria-hidden="true" />
            Fine Management
          </h1>
          <p className="text-text-muted text-sm mt-1">Collect and track library penalties</p>
        </div>
        <div className="px-6 py-3 bg-surface border border-border rounded-xl shadow-sm flex items-center gap-4">
          <span className="text-sm font-bold text-text-muted uppercase tracking-wider">Total Outstanding</span>
          <span className="text-2xl font-black text-amber-600 dark:text-amber-400">${totalOutstanding.toFixed(2)}</span>
        </div>
      </div>

      <div className="ng-table-container">
        <div className="p-4 border-b border-border bg-background-alt/30">
          <div className="relative w-full md:w-96">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={18} aria-hidden="true" />
            <input
              type="text"
              placeholder="Search by member or book title..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-surface border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm text-text"
            />
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="ng-table">
            <thead className="ng-table-header">
              <tr>
                <th>Member Details</th>
                <th>Fine Info</th>
                <th>Amount</th>
                <th>Status</th>
                <th className="text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50 text-sm">
              {loading ? (
                <tr><td colSpan={5} className="px-6 py-12 text-center text-text-muted">Loading records...</td></tr>
              ) : filteredFines.length === 0 ? (
                <tr><td colSpan={5} className="px-6 py-12 text-center text-text-muted">No fines found</td></tr>
              ) : (
                filteredFines.map((fine) => (
                  <tr key={fine.id} className="ng-table-row group">
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded bg-primary-50 dark:bg-primary-900/20 flex items-center justify-center">
                          <User size={16} className="text-primary" aria-hidden="true" />
                        </div>
                        <div>
                          <p className="font-bold text-text">{fine.first_name} {fine.last_name}</p>
                          <p className="text-[0.7rem] text-text-muted truncate max-w-[150px]">{fine.book_title}</p>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-[0.7rem] text-text-secondary font-medium">
                          <FileText size={12} className="text-primary" aria-hidden="true" />
                          <span>{fine.reason}</span>
                        </div>
                        <div className="flex items-center gap-2 text-[0.7rem] text-text-muted">
                          <Calendar size={12} aria-hidden="true" />
                          <span>Added: {new Date(fine.created_at).toLocaleDateString()}</span>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell font-black text-text">
                      ${fine.amount.toFixed(2)}
                    </td>
                    <td className="ng-table-cell">
                      <span className={`ng-table-badge ${
                        fine.status === 'paid' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' : 
                        fine.status === 'waived' ? 'bg-slate-50 dark:bg-slate-900/20 text-slate-700 dark:text-slate-400 border-slate-200 dark:border-slate-800' :
                        'bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 border-amber-100 dark:border-amber-900/30'
                      }`}>
                        {fine.status}
                      </span>
                    </td>
                    <td className="ng-table-cell text-right">
                      {fine.status === 'unpaid' && (
                        <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                          <button
                            onClick={() => handlePay(fine.id)}
                            className="px-3 py-1.5 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors text-xs font-bold flex items-center gap-1.5 cursor-pointer shadow-sm"
                            title="Mark as Paid"
                          >
                            <CheckCircle2 size={14} aria-hidden="true" />
                            Pay
                          </button>
                          <button
                            onClick={() => handleWaive(fine.id)}
                            className="px-3 py-1.5 bg-surface border border-border text-text-secondary rounded-lg hover:bg-background-alt transition-colors text-xs font-bold flex items-center gap-1.5 cursor-pointer"
                            title="Waive Fine"
                          >
                            <XCircle size={14} aria-hidden="true" />
                            Waive
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
