import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
  Brain, AlertCircle, Sparkles, Save, X,
  User, FileText, MessageSquare
} from 'lucide-react';
import { useTeacherStore } from '../store/teacher';

interface StudentSocialDocProps {
  student: any;
  onClose: () => void;
  onSaved?: () => void;
}

const LEARNER_TYPES = [
  { value: '', label: 'Select learner type...' },
  { value: 'Visual', label: 'Visual — learns best with images, diagrams, color' },
  { value: 'Auditory', label: 'Auditory — learns best through listening & discussion' },
  { value: 'Kinesthetic', label: 'Kinesthetic — learns best through hands-on activity' },
  { value: 'Reading/Writing', label: 'Reading/Writing — learns best through text & notes' },
  { value: 'Multimodal', label: 'Multimodal — combines several styles' },
];

const PARENT_AVAILABILITY = [
  { value: '', label: 'Select...' },
  { value: 'Both', label: 'Both parents available' },
  { value: 'Mother Only', label: 'Mother only' },
  { value: 'Father Only', label: 'Father only' },
  { value: 'Guardian', label: 'Guardian' },
  { value: 'Other Family', label: 'Other family member' },
  { value: 'None', label: 'None / limited contact' },
];

export function StudentSocialDoc({ student, onClose, onSaved }: StudentSocialDocProps) {
  const { currentStudentDoc, fetchStudentDoc, saveStudentSocialDoc } = useTeacherStore();
  const [formData, setFormData] = useState<any>({
    learner_type: '',
    past_behavior: '',
    family_size: '',
    parents_available: '',
    home_environment: '',
    medical_notes: '',
    social_strengths: '',
    social_challenges: '',
    interests: '',
    other_data: ''
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    if (student?.uid) {
      fetchStudentDoc(student.uid);
    }
  }, [student?.uid]);

  useEffect(() => {
    if (currentStudentDoc && !currentStudentDoc._empty) {
      setFormData({
        learner_type: currentStudentDoc.learner_type || '',
        past_behavior: currentStudentDoc.past_behavior || '',
        family_size: currentStudentDoc.family_size ?? '',
        parents_available: currentStudentDoc.parents_available || '',
        home_environment: currentStudentDoc.home_environment || '',
        medical_notes: currentStudentDoc.medical_notes || '',
        social_strengths: currentStudentDoc.social_strengths || '',
        social_challenges: currentStudentDoc.social_challenges || '',
        interests: currentStudentDoc.interests || '',
        other_data: currentStudentDoc.other_data || '',
      });
    } else if (currentStudentDoc?._empty) {
      setFormData({
        learner_type: '', past_behavior: '', family_size: '',
        parents_available: '', home_environment: '', medical_notes: '',
        social_strengths: '', social_challenges: '', interests: '', other_data: ''
      });
    }
  }, [currentStudentDoc]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    setSuccess(false);
    try {
      await saveStudentSocialDoc({
        student_id: student.id,
        ...formData,
      });
      setSuccess(true);
      onSaved?.();
      setTimeout(() => onClose(), 600);
    } catch (err: any) {
      setError(err?.response?.data?.error || err?.message || 'Failed to save social document');
    } finally {
      setSaving(false);
    }
  };

  const update = (k: string, v: any) => setFormData({ ...formData, [k]: v });

  return createPortal(
    <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[160] flex items-center justify-center p-4 animate-in fade-in duration-300" onClick={onClose}>
      <div className="bg-card rounded-[2.5rem] w-full max-w-3xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className="p-8 pb-6 bg-muted/50 border-b border-border flex items-center justify-between shrink-0 relative overflow-hidden">
          <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
            <Brain size={180} />
          </div>
          <div className="relative z-10 flex items-center gap-5">
            <div className="w-16 h-16 rounded-2xl bg-card border border-border shadow-lg flex items-center justify-center text-primary">
              <User size={28} />
            </div>
            <div>
              <h2 className="text-2xl font-black text-text tracking-tight uppercase">
                Social Profile
              </h2>
              <p className="text-[0.7rem] font-bold text-text-muted uppercase tracking-widest mt-1">
                {student.first_name} {student.last_name} · Holistic Learner Snapshot
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="relative z-10 w-11 h-11 flex items-center justify-center rounded-2xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm"
            aria-label="Close"
          >
            <X size={22} />
          </button>
        </div>

        {/* Body */}
        <form onSubmit={handleSubmit} className="p-8 overflow-y-auto flex-1 custom-scrollbar space-y-7">

          {error && (
            <div className="p-4 bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-800 rounded-2xl flex items-start gap-3">
              <AlertCircle size={18} className="text-rose-500 mt-0.5 shrink-0" />
              <p className="text-sm font-medium text-rose-700 dark:text-rose-300">{error}</p>
            </div>
          )}

          {/* Learning & Behavior */}
          <section>
            <SectionHeader icon={<Lightbulb size={18} />} color="amber" title="Learning & Behavior" />
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Field label="Learner Type" hint="How does this student learn best?">
                <select
                  className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-amber-500/10 focus:bg-card focus:border-amber-500/30 transition-all"
                  value={formData.learner_type}
                  onChange={e => update('learner_type', e.target.value)}
                >
                  {LEARNER_TYPES.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </Field>
              <Field label="Family Size">
                <input
                  type="number" min="0" max="20"
                  className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-amber-500/10 focus:bg-card focus:border-amber-500/30 transition-all"
                  value={formData.family_size}
                  onChange={e => update('family_size', e.target.value)}
                  placeholder="e.g., 5"
                />
              </Field>
              <div className="md:col-span-2">
                <Field label="Past Behavior Notes" hint="Behavior patterns from previous years that inform how to approach this student">
                  <textarea
                    className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-amber-500/10 focus:bg-card focus:border-amber-500/30 transition-all min-h-[80px]"
                    value={formData.past_behavior}
                    onChange={e => update('past_behavior', e.target.value)}
                    placeholder="Engagement patterns, triggers, what works, what doesn't..."
                  />
                </Field>
              </div>
            </div>
          </section>

          {/* Family & Home */}
          <section>
            <SectionHeader icon={<Home size={18} />} color="emerald" title="Family & Home Environment" />
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Field label="Parents Available">
                <select
                  className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-emerald-500/10 focus:bg-card focus:border-emerald-500/30 transition-all"
                  value={formData.parents_available}
                  onChange={e => update('parents_available', e.target.value)}
                >
                  {PARENT_AVAILABILITY.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </Field>
              <Field label="Interests & Hobbies" hint="What lights this student up outside of class?">
                <input
                  className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-emerald-500/10 focus:bg-card focus:border-emerald-500/30 transition-all"
                  value={formData.interests}
                  onChange={e => update('interests', e.target.value)}
                  placeholder="e.g., Netball, chess club, coding..."
                />
              </Field>
              <div className="md:col-span-2">
                <Field label="Home Setup" hint="Living situation, study space, family dynamics, who lives with the student">
                  <textarea
                    className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-emerald-500/10 focus:bg-card focus:border-emerald-500/30 transition-all min-h-[80px]"
                    value={formData.home_environment}
                    onChange={e => update('home_environment', e.target.value)}
                    placeholder="Household composition, study environment, language(s), socioeconomic notes..."
                  />
                </Field>
              </div>
            </div>
          </section>

          {/* Social & Health */}
          <section>
            <SectionHeader icon={<HeartPulse size={18} />} color="rose" title="Social & Health" />
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Field label="Social Strengths" hint="What does this student excel at socially?">
                <textarea
                  className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-rose-500/10 focus:bg-card focus:border-rose-500/30 transition-all min-h-[80px]"
                  value={formData.social_strengths}
                  onChange={e => update('social_strengths', e.target.value)}
                  placeholder="Leader, listener, helper, group dynamics..."
                />
              </Field>
              <Field label="Social Challenges" hint="What does the student struggle with socially?">
                <textarea
                  className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-rose-500/10 focus:bg-card focus:border-rose-500/30 transition-all min-h-[80px]"
                  value={formData.social_challenges}
                  onChange={e => update('social_challenges', e.target.value)}
                  placeholder="Anxiety, conflict, shyness, communication..."
                />
              </Field>
              <div className="md:col-span-2">
                <Field label="Medical Notes" hint="Confidential — allergies, conditions, medications kept at school">
                  <textarea
                    className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-rose-500/10 focus:bg-card focus:border-rose-500/30 transition-all min-h-[80px]"
                    value={formData.medical_notes}
                    onChange={e => update('medical_notes', e.target.value)}
                    placeholder="Allergies, chronic conditions, medications, last check-up..."
                  />
                </Field>
              </div>
              <div className="md:col-span-2">
                <Field label="Additional Notes" hint="Anything else the next teacher should know (guardians, languages, etc.)">
                  <textarea
                    className="w-full bg-muted/30 border border-border rounded-xl px-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-rose-500/10 focus:bg-card focus:border-rose-500/30 transition-all min-h-[70px]"
                    value={formData.other_data}
                    onChange={e => update('other_data', e.target.value)}
                    placeholder="Languages spoken at home, custody arrangements, anything notable..."
                  />
                </Field>
              </div>
            </div>
          </section>

          {/* Actions */}
          <div className="flex justify-end gap-3 pt-4 border-t border-border">
            <button
              type="button"
              onClick={onClose}
              className="px-6 py-3 bg-muted/50 hover:bg-muted text-text-muted hover:text-text rounded-2xl text-[0.7rem] font-black uppercase tracking-widest transition-all border border-border"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving}
              className="px-7 py-3 bg-primary hover:bg-primary/90 disabled:opacity-50 text-white rounded-2xl text-[0.7rem] font-black uppercase tracking-widest transition-all shadow-lg shadow-blue-900/20 flex items-center gap-2"
            >
              {saving ? <Loader2 size={16} className="animate-spin" /> :
               success ? <CheckCircle2 size={16} /> :
               <Save size={16} />}
              {success ? 'Saved' : saving ? 'Saving...' : 'Save Profile'}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
    document.body
  );
}

function SectionHeader({ icon, color, title }: { icon: React.ReactNode; color: 'amber' | 'emerald' | 'rose'; title: string }) {
  const palette = {
    amber:   { text: 'text-amber-600 dark:text-amber-400',   bg: 'bg-amber-50/10 dark:bg-amber-900/10 border-amber-100/20' },
    emerald: { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50/10 dark:bg-emerald-900/10 border-emerald-100/20' },
    rose:    { text: 'text-rose-600 dark:text-rose-400',       bg: 'bg-rose-50/10 dark:bg-rose-900/10 border-rose-100/20' },
  }[color];
  return (
    <div className={`flex items-center gap-3 mb-4 px-4 py-3 ${palette.bg} border rounded-2xl`}>
      <div className={`${palette.text}`}>{icon}</div>
      <h3 className={`text-[0.65rem] font-black uppercase tracking-[3px] ${palette.text}`}>{title}</h3>
    </div>
  );
}

function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-2">{label}</label>
      {children}
      {hint && <p className="text-[0.6rem] text-text-muted/70 mt-1.5 italic">{hint}</p>}
    </div>
  );
}