import { useState } from 'react';
import { useBatchStore } from '@/stores/batchStore';
import { useStudentStore } from '@/stores/studentStore';
import { useUIStore } from '@/stores/uiStore';
import { ChevronLeft, Plus, Users, Clock, Trash2, Pencil, Check, X } from 'lucide-react';

export default function BatchManagementScreen() {
  const { batches, createBatch, updateBatch, deleteBatch } = useBatchStore();
  const { students } = useStudentStore();
  const { goBack, showToast } = useUIStore();

  const [showAdd, setShowAdd] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  const [form, setForm] = useState<{ name: string; timing: string; skillLevel: 'beginner' | 'intermediate' | 'advanced'; maxCapacity: number; monthlyFee: number }>({ name: '', timing: '', skillLevel: 'beginner', maxCapacity: 20, monthlyFee: 1500 });

  const handleAdd = async () => {
    if (!form.name.trim()) { showToast({ type: 'error', message: 'Batch name required' }); return; }
    await createBatch(form);
    setForm({ name: '', timing: '', skillLevel: 'beginner', maxCapacity: 20, monthlyFee: 1500 });
    setShowAdd(false);
    showToast({ type: 'success', message: 'Batch created!' });
  };

  const handleUpdate = async (id: number) => {
    await updateBatch(id, form);
    setEditingId(null);
    showToast({ type: 'success', message: 'Batch updated!' });
  };

  const handleDelete = async (id: number, name: string) => {
    await deleteBatch(id);
    showToast({ type: 'info', message: `Batch "${name}" deleted` });
  };

  const skillColors: Record<string, string> = { beginner: 'bg-emerald-100 text-emerald-700', intermediate: 'bg-blue-100 text-blue-700', advanced: 'bg-purple-100 text-purple-700' };

  return (
    <div className="px-4 pt-4 pb-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <button onClick={goBack} className="p-1"><ChevronLeft className="w-5 h-5 text-gray-500" /></button>
          <h2 className="text-lg font-bold text-gray-900">Manage Batches</h2>
        </div>
        <button onClick={() => setShowAdd(true)}
          className="w-9 h-9 brand-gradient rounded-xl flex items-center justify-center text-white shadow-md active:scale-90 transition-transform">
          <Plus className="w-4 h-4" />
        </button>
      </div>

      {/* Stats */}
      <div className="bg-orange-50 rounded-2xl p-4 mb-4 flex items-center gap-4">
        <div className="w-12 h-12 bg-orange-100 rounded-xl flex items-center justify-center">
          <Users className="w-6 h-6 text-orange-500" />
        </div>
        <div>
          <p className="text-2xl font-bold text-gray-900">{batches.length}</p>
          <p className="text-xs text-gray-500">Batches</p>
        </div>
      </div>

      {/* Batch List */}
      <div className="space-y-3">
        {batches.length === 0 && (
          <div className="text-center py-10">
            <Users className="w-10 h-10 text-gray-200 mx-auto mb-2" />
            <p className="text-xs text-gray-400">No batches yet. Create your first batch!</p>
          </div>
        )}

        {batches.map(batch => {
          const count = students.filter(s => s.isActive && s.batchId === batch.id).length;
          return (
            <div key={batch.id} className="bg-white rounded-2xl p-4 card-shadow">
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-bold text-gray-900">{batch.name}</p>
                    <span className={`px-1.5 py-0.5 text-[9px] font-bold rounded ${skillColors[batch.skillLevel] || 'bg-gray-100'}`}>{batch.skillLevel}</span>
                  </div>
                  <div className="flex items-center gap-3 mt-1">
                    <span className="flex items-center gap-1 text-[10px] text-gray-400"><Clock className="w-3 h-3" />{batch.timing}</span>
                    <span className="flex items-center gap-1 text-[10px] text-gray-400"><Users className="w-3 h-3" />{count}/{batch.maxCapacity} students</span>
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  <button onClick={() => { setEditingId(batch.id); setForm({ name: batch.name, timing: batch.timing, skillLevel: batch.skillLevel, maxCapacity: batch.maxCapacity, monthlyFee: batch.monthlyFee }); }}
                    className="p-2 text-gray-300 hover:text-orange-500 transition-colors">
                    <Pencil className="w-4 h-4" />
                  </button>
                  <button onClick={() => handleDelete(batch.id, batch.name)}
                    className="p-2 text-gray-300 hover:text-red-500 transition-colors">
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Add Batch Modal */}
      {showAdd && (
        <div className="fixed inset-0 z-[60] flex items-end">
          <div className="absolute inset-0 bg-black/40" onClick={() => setShowAdd(false)} />
          <div className="relative bg-white rounded-t-3xl w-full max-w-lg mx-auto p-6 pb-10 animate-slide-up">
            <div className="w-10 h-1 bg-gray-300 rounded-full mx-auto mb-5" />
            <h3 className="text-lg font-bold text-gray-900 mb-4">Create New Batch</h3>
            <div className="space-y-3">
              <input type="text" value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} placeholder="Batch name" className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
              <input type="text" value={form.timing} onChange={e => setForm(p => ({ ...p, timing: e.target.value }))} placeholder="Timing (e.g. 6:00 AM - 8:00 AM)" className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
              <select value={form.skillLevel} onChange={e => setForm(p => ({ ...p, skillLevel: e.target.value as 'beginner' | 'intermediate' | 'advanced' }))} className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm">
                <option value="beginner">Beginner</option>
                <option value="intermediate">Intermediate</option>
                <option value="advanced">Advanced</option>
              </select>
              <div className="grid grid-cols-2 gap-3">
                <input type="number" value={form.maxCapacity} onChange={e => setForm(p => ({ ...p, maxCapacity: parseInt(e.target.value) || 20 }))} placeholder="Max capacity" className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
                <input type="number" value={form.monthlyFee} onChange={e => setForm(p => ({ ...p, monthlyFee: parseInt(e.target.value) || 1500 }))} placeholder="Monthly fee" className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
              </div>
              <button onClick={handleAdd} className="w-full h-14 brand-gradient text-white font-bold rounded-2xl button-shadow active:scale-[0.97] transition-transform">Create Batch</button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Batch Modal */}
      {editingId !== null && (
        <div className="fixed inset-0 z-[60] flex items-end">
          <div className="absolute inset-0 bg-black/40" onClick={() => setEditingId(null)} />
          <div className="relative bg-white rounded-t-3xl w-full max-w-lg mx-auto p-6 pb-10 animate-slide-up">
            <div className="w-10 h-1 bg-gray-300 rounded-full mx-auto mb-5" />
            <h3 className="text-lg font-bold text-gray-900 mb-4">Edit Batch</h3>
            <div className="space-y-3">
              <input type="text" value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
              <input type="text" value={form.timing} onChange={e => setForm(p => ({ ...p, timing: e.target.value }))} className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
              <div className="grid grid-cols-2 gap-3">
                <input type="number" value={form.maxCapacity} onChange={e => setForm(p => ({ ...p, maxCapacity: parseInt(e.target.value) || 20 }))} className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
                <input type="number" value={form.monthlyFee} onChange={e => setForm(p => ({ ...p, monthlyFee: parseInt(e.target.value) || 1500 }))} className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm" />
              </div>
              <button onClick={() => handleUpdate(editingId)} className="w-full h-14 brand-gradient text-white font-bold rounded-2xl button-shadow active:scale-[0.97] transition-transform">Save Changes</button>
              <button onClick={() => setEditingId(null)} className="w-full py-2 text-gray-400 text-sm">Cancel</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
