import { useState } from 'react';
import { useStudentStore } from '@/stores/studentStore';
import { useUIStore } from '@/stores/uiStore';
import { Avatar } from '@/components/common';
import { IndianRupee, Check, Search } from 'lucide-react';

type FilterType = 'all' | 'paid' | 'due' | 'pending';

export default function CoachFeeScreen() {
  const { students, toggleFeeStatus } = useStudentStore();
  const { showToast } = useUIStore();
  const [searchQuery, setSearchQuery] = useState('');
  const [filter, setFilter] = useState<FilterType>('all');

  const activeStudents = students.filter(s => s.isActive);

  const filtered = activeStudents.filter(s => {
    if (filter !== 'all' && s.feeStatus !== filter) return false;
    if (searchQuery && !s.fullName.toLowerCase().includes(searchQuery.toLowerCase()) && !s.studentId.toLowerCase().includes(searchQuery.toLowerCase())) return false;
    return true;
  });

  const handleToggle = (id: number, name: string, currentStatus: string) => {
    toggleFeeStatus(id);
    const newStatus = currentStatus === 'paid' ? 'Due' : 'Paid';
    showToast({ type: 'success', message: `${name} marked as ${newStatus}` });
  };

  return (
    <div className="px-4 pt-4 pb-4 space-y-4">
      {/* Header */}
      <h2 className="text-lg font-bold text-gray-900">Fee Status</h2>

      {/* Summary Bar */}
      <div className="grid grid-cols-4 gap-2">
        {([
          { key: 'all', label: 'All', count: activeStudents.length },
          { key: 'paid', label: 'Paid', count: activeStudents.filter(s => s.feeStatus === 'paid').length },
          { key: 'due', label: 'Due', count: activeStudents.filter(s => s.feeStatus === 'due').length },
          { key: 'pending', label: 'Pending', count: activeStudents.filter(s => s.feeStatus === 'pending').length },
        ] as { key: FilterType; label: string; count: number }[]).map(f => (
          <button key={f.key} onClick={() => setFilter(f.key)}
            className={`py-2 rounded-xl text-xs font-semibold text-center transition-all ${
              filter === f.key
                ? 'bg-orange-500 text-white shadow-md'
                : 'bg-gray-100 text-gray-500'
            }`}>
            {f.label}
            <span className="block text-[10px] opacity-70 mt-0.5">{f.count}</span>
          </button>
        ))}
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
        <input
          type="text"
          value={searchQuery}
          onChange={e => setSearchQuery(e.target.value)}
          placeholder="Search student..."
          className="w-full h-11 pl-9 pr-4 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/15 transition-all"
        />
      </div>

      {/* Student List with Paid/Due Toggle */}
      <div className="space-y-2">
        {filtered.length === 0 && (
          <div className="text-center py-10">
            <IndianRupee className="w-10 h-10 text-gray-200 mx-auto mb-2" />
            <p className="text-xs text-gray-400">No students found</p>
          </div>
        )}

        {filtered.map(student => {
          const isPaid = student.feeStatus === 'paid';
          return (
            <div key={student.id}
              className={`bg-white rounded-2xl p-4 card-shadow flex items-center gap-3 ${isPaid ? 'border-l-4 border-emerald-400' : 'border-l-4 border-amber-400'}`}>
              <Avatar name={student.fullName} size="sm" />

              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-gray-900 truncate">{student.fullName}</p>
                <p className="text-[10px] text-gray-400">{student.studentId}</p>
              </div>

              {/* Paid/Due Toggle Button */}
              <button
                onClick={() => handleToggle(student.id, student.fullName, student.feeStatus || 'pending')}
                className={`px-4 py-2.5 rounded-xl text-xs font-bold flex items-center gap-1.5 transition-all active:scale-90 ${
                  isPaid
                    ? 'bg-emerald-100 text-emerald-700 border border-emerald-200'
                    : 'bg-amber-100 text-amber-700 border border-amber-200'
                }`}
              >
                {isPaid ? (
                  <>
                    <Check className="w-3.5 h-3.5" />
                    Paid
                  </>
                ) : (
                  <>
                    <IndianRupee className="w-3.5 h-3.5" />
                    Not Paid
                  </>
                )}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
