import { useState } from 'react';
import { useStudentStore } from '@/stores/studentStore';
import { useBatchStore } from '@/stores/batchStore';
import { useUIStore } from '@/stores/uiStore';
import { WhatsAppButton } from '@/components/common';
import { format } from 'date-fns';
import { Check, Copy, X } from 'lucide-react';

export default function AddStudentScreen() {
  const { addStudent } = useStudentStore();
  const { batches } = useBatchStore();
  const { goBack, showToast } = useUIStore();
  const [step, setStep] = useState<'form' | 'success'>('form');
  const [credentials, setCredentials] = useState<{ studentId: string; password: string } | null>(null);
  const [copied, setCopied] = useState(false);

  const [form, setForm] = useState({
    fullName: '', dateOfBirth: '', gender: 'male' as const, phone: '', email: '',
    guardianName: '', guardianPhone: '', guardianRelationship: 'parent' as const,
    batchId: batches[0]?.id || 1, skillLevel: 'beginner' as const, monthlyFee: 1500,
    joiningDate: format(new Date(), 'yyyy-MM-dd'),
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleChange = (field: string, value: unknown) => {
    setForm(prev => ({ ...prev, [field]: value }));
    if (errors[field]) setErrors(prev => { const n = { ...prev }; delete n[field]; return n; });
  };

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

  const handleSubmit = async () => {
    if (!validate()) return;
    const result = await addStudent(form);
    setCredentials(result);
    setStep('success');
    showToast({ type: 'success', message: 'Student added successfully!' });
  };

  const copyCreds = () => {
    if (credentials) {
      navigator.clipboard.writeText(`ID: ${credentials.studentId}\nPassword: ${credentials.password}`);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  if (step === 'success' && credentials) {
    return (
      <div className="px-4 pt-4 pb-4 flex flex-col items-center justify-center min-h-[60vh]">
        <div className="w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
          <Check className="w-8 h-8 text-emerald-500" />
        </div>
        <h2 className="text-xl font-bold text-gray-900">Student Added!</h2>
        <p className="text-sm text-gray-500 mt-1">Login credentials generated</p>
        <div className="w-full bg-gray-50 rounded-xl p-4 mt-6 space-y-2">
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">Student ID</span>
            <span className="font-mono font-bold text-gray-900">{credentials.studentId}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">Password</span>
            <span className="font-mono font-bold text-gray-900">{credentials.password}</span>
          </div>
        </div>
        <button onClick={copyCreds} className="mt-3 flex items-center gap-2 text-sm text-orange-500 font-medium">
          {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
          {copied ? 'Copied!' : 'Copy Credentials'}
        </button>
        {form.phone && (
          <div className="mt-3">
            <WhatsAppButton phone={form.phone} message={`Welcome to SkatePro Academy! Your login details:\nID: ${credentials.studentId}\nPassword: ${credentials.password}`} />
          </div>
        )}
        <button onClick={goBack} className="mt-6 w-full py-3 brand-gradient text-white font-semibold rounded-xl button-shadow">
          Done
        </button>
      </div>
    );
  }

  const inputClass = (field: string) => `w-full h-12 px-4 bg-white border ${errors[field] ? 'border-red-400' : 'border-gray-200'} rounded-xl text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/15 transition-all`;
  const labelClass = "block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide";

  return (
    <div className="px-4 pt-4 pb-4">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-900">Add New Student</h2>
        <button onClick={goBack} className="p-2 -mr-2"><X className="w-5 h-5 text-gray-500" /></button>
      </div>

      <div className="space-y-4">
        <div>
          <label className={labelClass}>Full Name *</label>
          <input type="text" value={form.fullName} onChange={e => handleChange('fullName', e.target.value)} placeholder="Enter full name" className={inputClass('fullName')} />
          {errors.fullName && <p className="text-xs text-red-500 mt-1">{errors.fullName}</p>}
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Date of Birth *</label>
            <input type="date" value={form.dateOfBirth} onChange={e => handleChange('dateOfBirth', e.target.value)} className={inputClass('dateOfBirth')} />
          </div>
          <div>
            <label className={labelClass}>Gender</label>
            <select value={form.gender} onChange={e => handleChange('gender', e.target.value)} className={inputClass('gender')}>
              <option value="male">Male</option>
              <option value="female">Female</option>
              <option value="other">Other</option>
            </select>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Phone *</label>
            <input type="tel" value={form.phone} onChange={e => handleChange('phone', e.target.value)} placeholder="10 digit number" className={inputClass('phone')} />
          </div>
          <div>
            <label className={labelClass}>Email</label>
            <input type="email" value={form.email} onChange={e => handleChange('email', e.target.value)} placeholder="Optional" className={inputClass('email')} />
          </div>
        </div>

        <div>
          <label className={labelClass}>Guardian Name *</label>
          <input type="text" value={form.guardianName} onChange={e => handleChange('guardianName', e.target.value)} placeholder="Parent/Guardian name" className={inputClass('guardianName')} />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Guardian Phone *</label>
            <input type="tel" value={form.guardianPhone} onChange={e => handleChange('guardianPhone', e.target.value)} placeholder="10 digit number" className={inputClass('guardianPhone')} />
          </div>
          <div>
            <label className={labelClass}>Relationship</label>
            <select value={form.guardianRelationship} onChange={e => handleChange('guardianRelationship', e.target.value)} className={inputClass('guardianRelationship')}>
              <option value="parent">Parent</option>
              <option value="sibling">Sibling</option>
              <option value="other">Other</option>
            </select>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Batch *</label>
            <select value={form.batchId} onChange={e => handleChange('batchId', parseInt(e.target.value))} className={inputClass('batchId')}>
              {batches.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
            </select>
          </div>
          <div>
            <label className={labelClass}>Skill Level</label>
            <select value={form.skillLevel} onChange={e => handleChange('skillLevel', e.target.value)} className={inputClass('skillLevel')}>
              <option value="beginner">Beginner</option>
              <option value="intermediate">Intermediate</option>
              <option value="advanced">Advanced</option>
            </select>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Monthly Fee</label>
            <input type="number" value={form.monthlyFee} onChange={e => handleChange('monthlyFee', parseInt(e.target.value) || 0)} className={inputClass('monthlyFee')} />
          </div>
          <div>
            <label className={labelClass}>Joining Date</label>
            <input type="date" value={form.joiningDate} onChange={e => handleChange('joiningDate', e.target.value)} className={inputClass('joiningDate')} />
          </div>
        </div>

        <button onClick={handleSubmit} className="w-full h-12 brand-gradient text-white font-semibold rounded-xl button-shadow mt-2 active:scale-[0.98] transition-transform">
          Save Student
        </button>
      </div>
    </div>
  );
}
