import { useState, useEffect } from 'react';
import { useUIStore } from '@/stores/uiStore';
import { Avatar } from '@/components/common';
import { UserPlus, Copy, Check, X, Trash2, ChevronLeft, Users } from 'lucide-react';

interface Coach {
  id: number;
  username: string;
  name: string;
  phone: string;
  created_at: string;
  isNew?: boolean;
  tempPassword?: string;
}

// No demo coaches - starts empty
const demoCoaches: Coach[] = [];

export default function ManageCoachesScreen() {
  const { goBack, showToast } = useUIStore();
  const [coaches, setCoaches] = useState<Coach[]>([]);
  const [showAdd, setShowAdd] = useState(false);
  const [copiedId, setCopiedId] = useState<number | null>(null);

  const [form, setForm] = useState({ fullName: '', phone: '' });
  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    // Try to fetch from API, fallback to demo
    fetch('/api/coaches.php')
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) setCoaches(data);
        else setCoaches(demoCoaches);
      })
      .catch(() => setCoaches(demoCoaches));
  }, []);

  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.fullName.trim()) e.fullName = 'Required';
    if (!form.phone.match(/^\d{10}$/)) e.phone = '10 digits required';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleAdd = async () => {
    if (!validate()) return;

    const username = 'coach' + String(coaches.length + 1).padStart(3, '0');
    const password = Math.random().toString(36).slice(-8);

    const newCoach: Coach = {
      id: coaches.length + 10,
      username,
      name: form.fullName.trim(),
      phone: form.phone,
      created_at: new Date().toISOString(),
      isNew: true,
      tempPassword: password,
    };

    // Try API first
    try {
      await fetch('/api/coaches.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          username,
          name: form.fullName.trim(),
          phone: form.phone,
          password,
        }),
      });
    } catch { /* offline - keep local */ }

    setCoaches(prev => [newCoach, ...prev]);
    setForm({ fullName: '', phone: '' });
    setShowAdd(false);
    showToast({ type: 'success', message: `Coach ${newCoach.name} added! ID: ${username}` });
  };

  const handleDelete = async (id: number, name: string) => {
    try {
      await fetch(`/api/coaches.php?id=${id}`, { method: 'DELETE' });
    } catch { /* offline */ }
    setCoaches(prev => prev.filter(c => c.id !== id));
    showToast({ type: 'info', message: `Coach ${name} removed` });
  };

  const copyCreds = (coach: Coach) => {
    const text = `SkatePro Academy - Coach Login\nID: ${coach.username}\nPassword: ${coach.tempPassword || 'assistant123'}\n\nLogin at: yourwebsite.com/#/coach`;
    navigator.clipboard.writeText(text);
    setCopiedId(coach.id);
    setTimeout(() => setCopiedId(null), 2000);
    showToast({ type: 'success', message: 'Credentials copied!' });
  };

  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 Coaches</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">
          <UserPlus className="w-4 h-4" />
        </button>
      </div>

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

      {/* Coaches List */}
      <div className="space-y-3">
        {coaches.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 coaches added yet</p>
          </div>
        )}

        {coaches.map(coach => (
          <div key={coach.id} className={`bg-white rounded-2xl p-4 card-shadow ${coach.isNew ? 'border-l-4 border-emerald-400' : ''}`}>
            <div className="flex items-center gap-3">
              <Avatar name={coach.name} size="md" />
              <div className="flex-1">
                <p className="text-sm font-semibold text-gray-900">{coach.name}</p>
                <p className="text-[10px] text-gray-400">ID: {coach.username}</p>
                {coach.phone && <p className="text-[10px] text-gray-400">{coach.phone}</p>}
              </div>
              <div className="flex items-center gap-1">
                {coach.isNew && coach.tempPassword && (
                  <button onClick={() => copyCreds(coach)}
                    className="p-2 text-emerald-500 hover:bg-emerald-50 rounded-xl transition-colors">
                    {copiedId === coach.id ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                  </button>
                )}
                <button onClick={() => handleDelete(coach.id, coach.name)}
                  className="p-2 text-gray-300 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors">
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </div>

            {/* New coach credentials */}
            {coach.isNew && coach.tempPassword && (
              <div className="mt-3 p-3 bg-emerald-50 rounded-xl">
                <p className="text-xs text-emerald-700 font-medium mb-1">Login Credentials (copy and share):</p>
                <div className="flex justify-between text-xs">
                  <span className="text-gray-500">Username</span>
                  <span className="font-mono font-bold text-gray-900">{coach.username}</span>
                </div>
                <div className="flex justify-between text-xs mt-1">
                  <span className="text-gray-500">Password</span>
                  <span className="font-mono font-bold text-gray-900">{coach.tempPassword}</span>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Add Coach 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-1">Add Assistant Coach</h3>
            <p className="text-xs text-gray-400 mb-4">Auto-generates login ID and password</p>

            <div className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase">Full Name *</label>
                <input type="text" value={form.fullName}
                  onChange={e => { setForm(p => ({ ...p, fullName: e.target.value })); if (errors.fullName) setErrors(p => { const n = { ...p }; delete n.fullName; return n; }); }}
                  placeholder="Coach name" className="w-full h-12 px-4 bg-white border border-gray-200 rounded-xl text-sm" />
                {errors.fullName && <p className="text-xs text-red-500 mt-1">{errors.fullName}</p>}
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5 uppercase">Phone *</label>
                <input type="tel" value={form.phone}
                  onChange={e => { setForm(p => ({ ...p, phone: e.target.value })); if (errors.phone) setErrors(p => { const n = { ...p }; delete n.phone; return n; }); }}
                  placeholder="10 digit number" className="w-full h-12 px-4 bg-white border border-gray-200 rounded-xl text-sm" />
                {errors.phone && <p className="text-xs text-red-500 mt-1">{errors.phone}</p>}
              </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">
                Add Coach & Generate Login
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
