import { useState, useEffect } from 'react';
import { 
  BookOpen, Users, Clock, AlertTriangle, 
  ArrowRight, Search, Plus, Filter,
  Book, Bookmark, History as HistoryIcon, CreditCard
} from 'lucide-react';
import api from '../../store/auth';
import { Link } from 'react-router-dom';

interface LibraryStats {
  totalBooks: number;
  availableBooks: number;
  issuedBooks: number;
  overdueBooks: number;
  totalFines: number;
  pendingReservations: number;
}

export default function LibrarianDashboard() {
  const [stats, setStats] = useState<LibraryStats>({
    totalBooks: 0,
    availableBooks: 0,
    issuedBooks: 0,
    overdueBooks: 0,
    totalFines: 0,
    pendingReservations: 0
  });
  const [recentIssues, setRecentIssues] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const [booksRes, issuesRes, reservationsRes, finesRes] = await Promise.all([
        api.get('/library/books'),
        api.get('/library/issues'),
        api.get('/library/reservations'),
        api.get('/library/fines')
      ]);

      const books = booksRes.data;
      const issues = issuesRes.data;
      const reservations = reservationsRes.data;
      const fines = finesRes.data;

      const activeIssues = issues.filter((i: any) => i.status === 'issued');
      const overdue = activeIssues.filter((i: any) => new Date(i.due_date) < new Date());

      setStats({
        totalBooks: books.reduce((acc: number, b: any) => acc + b.total_copies, 0),
        availableBooks: books.reduce((acc: number, b: any) => acc + b.available_copies, 0),
        issuedBooks: activeIssues.length,
        overdueBooks: overdue.length,
        totalFines: fines.filter((f: any) => f.status === 'unpaid').reduce((acc: number, f: any) => acc + f.amount, 0),
        pendingReservations: reservations.filter((r: any) => r.status === 'pending').length
      });

      setRecentIssues(issues.slice(0, 5));
    } catch (error) {
      console.error('Error fetching library stats:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const getColorClasses = (color: string) => {
    switch (color) {
      case 'blue':
        return {
          bg: 'bg-blue-50 dark:bg-blue-900/20',
          text: 'text-blue-600 dark:text-blue-400'
        };
      case 'emerald':
        return {
          bg: 'bg-emerald-50 dark:bg-emerald-900/20',
          text: 'text-emerald-600 dark:text-emerald-400'
        };
      case 'indigo':
        return {
          bg: 'bg-indigo-50 dark:bg-indigo-900/20',
          text: 'text-indigo-600 dark:text-indigo-400'
        };
      case 'red':
        return {
          bg: 'bg-red-50 dark:bg-red-900/20',
          text: 'text-red-600 dark:text-red-400'
        };
      default:
        return {
          bg: 'bg-muted',
          text: 'text-text-muted'
        };
    }
  };

  const statCards = [
    { label: 'Total Books', value: stats.totalBooks, icon: Book, color: 'blue' },
    { label: 'Available', value: stats.availableBooks, icon: BookOpen, color: 'emerald' },
    { label: 'Books Issued', value: stats.issuedBooks, icon: Clock, color: 'indigo' },
    { label: 'Overdue', value: stats.overdueBooks, icon: AlertTriangle, color: 'red' },
  ];

  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">Librarian Portal</h1>
          <p className="text-text-muted text-sm mt-1">Monitor and manage the campus library system</p>
        </div>
        <div className="flex gap-3">
          <Link
            to="/library/books"
            className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:opacity-90 transition-all shadow-sm font-semibold"
          >
            <Plus size={20} />
            Add Book
          </Link>
          <Link
            to="/library/issues?action=new"
            className="flex items-center gap-2 px-4 py-2 bg-surface border border-border text-text-secondary rounded-lg hover:bg-background-alt transition-colors shadow-sm font-semibold"
          >
            <HistoryIcon size={20} />
            Issue Book
          </Link>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        {statCards.map((s, i) => {
          const colors = getColorClasses(s.color);
          return (
            <div key={i} className="bg-surface p-6 rounded-xl border border-border shadow-sm">
              <div className="flex items-center justify-between mb-4">
                <div className={`w-12 h-12 rounded-lg ${colors.bg} ${colors.text} flex items-center justify-center`}>
                  <s.icon size={24} />
                </div>
                <span className={`${colors.text} ${colors.bg} px-2 py-1 rounded text-xs font-bold`}>
                  Live
                </span>
              </div>
              <p className="text-sm text-text-muted font-medium">{s.label}</p>
              <p className="text-2xl font-bold text-text mt-1">{s.value}</p>
            </div>
          );
        })}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-8">
          {/* Recent Activity */}
          <div className="ng-table-container overflow-hidden">
            <div className="px-6 py-4 border-b border-border flex items-center justify-between">
              <h3 className="font-bold text-text">Recent Transactions</h3>
              <Link to="/library/issues" className="text-primary text-sm font-semibold hover:underline">View All</Link>
            </div>
            <div className="overflow-x-auto">
              <table className="ng-table">
                <thead className="ng-table-header">
                  <tr>
                    <th className="px-6 py-3">Book</th>
                    <th className="px-6 py-3">Member</th>
                    <th className="px-6 py-3">Status</th>
                    <th className="px-6 py-3 text-right">Date</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/50">
                  {loading ? (
                    <tr><td colSpan={4} className="px-6 py-8 text-center text-text-muted">Loading activity...</td></tr>
                  ) : recentIssues.length === 0 ? (
                    <tr><td colSpan={4} className="px-6 py-8 text-center text-text-muted">No recent activity</td></tr>
                  ) : (
                    recentIssues.map((issue) => (
                      <tr key={issue.id} className="ng-table-row">
                        <td className="ng-table-cell">
                          <div className="text-sm font-semibold text-text">{issue.book_title}</div>
                          <div className="text-xs text-text-muted">{issue.book_author}</div>
                        </td>
                        <td className="ng-table-cell font-medium">
                          {issue.first_name} {issue.last_name}
                        </td>
                        <td className="ng-table-cell">
                          <span className={`ng-table-badge ${
                            issue.status === 'returned' 
                              ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' 
                              : 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 border-blue-100 dark:border-blue-900/30'
                          }`}>
                            {issue.status}
                          </span>
                        </td>
                        <td className="ng-table-cell text-right text-xs text-text-muted">
                          {new Date(issue.issue_date).toLocaleDateString()}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <div className="space-y-6">
          {/* Quick Actions / Fines */}
          <div className="bg-surface p-6 rounded-xl border border-border shadow-sm">
            <div className="flex items-center gap-3 mb-6">
              <div className="w-10 h-10 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 flex items-center justify-center">
                <CreditCard size={20} />
              </div>
              <div>
                <h3 className="font-bold text-text">Fine Collection</h3>
                <p className="text-xs text-text-muted">Pending library penalties</p>
              </div>
            </div>
            <div className="text-center py-4 bg-background-alt rounded-xl mb-4 border border-dashed border-border">
              <p className="text-sm text-text-muted mb-1">Total Outstanding</p>
              <p className="text-3xl font-black text-text">${stats.totalFines.toFixed(2)}</p>
            </div>
            <Link 
              to="/library/fines"
              className="w-full flex items-center justify-center gap-2 py-2.5 bg-surface border border-border text-text-secondary rounded-lg hover:bg-background-alt transition-colors font-semibold text-sm"
            >
              Collect Fines
              <ArrowRight size={16} />
            </Link>
          </div>

          <div className="bg-surface p-6 rounded-xl border border-border shadow-sm">
            <div className="flex items-center gap-3 mb-6">
              <div className="w-10 h-10 rounded-lg bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 flex items-center justify-center">
                <Bookmark size={20} />
              </div>
              <div>
                <h3 className="font-bold text-text">Reservations</h3>
                <p className="text-xs text-text-muted">Pending book requests</p>
              </div>
            </div>
            <div className="flex items-center justify-between p-4 bg-indigo-50/50 dark:bg-indigo-900/10 rounded-xl border border-indigo-100 dark:border-indigo-900/30">
              <span className="text-sm font-semibold text-indigo-900 dark:text-indigo-300">New Requests</span>
              <span className="px-2.5 py-0.5 bg-indigo-600 text-white rounded-full text-xs font-bold">{stats.pendingReservations}</span>
            </div>
            <Link 
              to="/library/reservations"
              className="w-full mt-4 flex items-center justify-center gap-2 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors font-semibold text-sm shadow-md shadow-indigo-200 dark:shadow-none"
            >
              Manage Requests
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
