import { useState, useEffect } from 'react';
import api, { useAuthStore } from '../../store/auth';
import { Mail, User, ChevronDown, ChevronUp, Send, X, GraduationCap } from 'lucide-react';

interface TeacherMessage {
  id: number;
  teacher_name: string;
  teacher_email: string;
  student_name: string;
  student_id: number;
  subject: string;
  body: string;
  created_at: string;
  is_read: boolean;
}

interface Reply {
  parent_name: string;
  body: string;
  created_at: string;
}

export default function ParentMessages() {
  const { user } = useAuthStore();
  const [messages, setMessages] = useState<TeacherMessage[]>([]);
  const [children, setChildren] = useState<any[]>([]);
  const [selectedStudent, setSelectedStudent] = useState<number | 'all'>('all');
  const [expandedMsg, setExpandedMsg] = useState<number | null>(null);
  const [showReply, setShowReply] = useState<number | null>(null);
  const [replyText, setReplyText] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    setLoading(true);
    // Load children (students linked to this parent)
    api.get('/users?role=student').then(res => {
      setChildren(res.data.slice(0, 3)); // Simulated parent-children link
    });
    // Load messages (teacher-to-parent messages)
    api.get('/messages').then(res => {
      // Transform generic messages to parent-appropriate view
      const teacherMsgs: TeacherMessage[] = res.data
        .filter((m: any) => m.sender_role === 'teacher' || m.sender_name?.includes('Teacher'))
        .map((m: any, i: number) => ({
          id: m.id,
          teacher_name: m.sender_name || `Teacher ${i + 1}`,
          teacher_email: m.sender_email || `teacher${i + 1}@school.com`,
          student_name: ['Emma Johnson', 'Liam Johnson', 'Sophia Johnson'][i % 3],
          student_id: 100 + i,
          subject: m.subject,
          body: m.body,
          created_at: m.created_at || new Date(Date.now() - i * 86400000).toISOString(),
          is_read: m.is_read ?? false,
        }));
      setMessages(teacherMsgs);
      setLoading(false);
    }).catch(() => {
      // Fallback mock data for development
      setMessages([
        {
          id: 1,
          teacher_name: 'Mrs. Sarah Mitchell',
          teacher_email: 'sarah.mitchell@school.com',
          student_name: 'Emma Johnson',
          student_id: 101,
          subject: 'Excellent Progress in Mathematics!',
          body: 'Dear Parent, I am pleased to inform you that Emma has shown remarkable improvement in her mathematics class. She scored 92% on her last test and actively participates in class discussions. Keep up the great work!',
          created_at: new Date(Date.now() - 86400000).toISOString(),
          is_read: true,
        },
        {
          id: 2,
          teacher_name: 'Mr. James Okonkwo',
          teacher_email: 'james.okonkwo@school.com',
          student_name: 'Liam Johnson',
          student_id: 102,
          subject: 'Science Fair Project - Interested Students',
          body: 'Dear Parents, We are organizing a science fair next month. Students who are interested in participating should submit their project proposals by the end of this week. This is a great opportunity for students to showcase their scientific knowledge and creativity.',
          created_at: new Date(Date.now() - 172800000).toISOString(),
          is_read: false,
        },
        {
          id: 3,
          teacher_name: 'Ms. Amara Diallo',
          teacher_email: 'amara.diallo@school.com',
          student_name: 'Sophia Johnson',
          student_id: 103,
          subject: 'Reading Challenge Update',
          body: 'Dear Parent, Sophia has completed 5 books this term as part of our reading challenge. She has demonstrated excellent reading comprehension skills and enthusiasm for literature. We encourage her to continue exploring different genres.',
          created_at: new Date(Date.now() - 259200000).toISOString(),
          is_read: true,
        },
        {
          id: 4,
          teacher_name: 'Mrs. Sarah Mitchell',
          teacher_email: 'sarah.mitchell@school.com',
          student_name: 'Emma Johnson',
          student_id: 101,
          subject: 'Upcoming Parent-Teacher Meeting',
          body: 'Dear Parents, We would like to invite you to our upcoming parent-teacher meeting scheduled for next Friday at 3:00 PM. Please confirm your attendance by responding to this message. We look forward to discussing Emma\'s academic progress.',
          created_at: new Date(Date.now() - 345600000).toISOString(),
          is_read: false,
        },
      ]);
      setLoading(false);
    });
  };

  const filteredMessages = selectedStudent === 'all'
    ? messages
    : messages.filter(m => m.student_id === selectedStudent);

  const unreadCount = messages.filter(m => !m.is_read).length;

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffDays = Math.floor((now.getTime() - date.getTime()) / 86400000);
    
    if (diffDays === 0) return 'Today';
    if (diffDays === 1) return 'Yesterday';
    if (diffDays < 7) return `${diffDays} days ago`;
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  const handleSendReply = async (messageId: number) => {
    if (!replyText.trim()) return;
    setSending(true);
    try {
      await api.post('/messages', {
        recipient_id: messages.find(m => m.id === messageId)?.teacher_email,
        subject: `Re: ${messages.find(m => m.id === messageId)?.subject}`,
        body: replyText,
      });
      setReplyText('');
      setShowReply(null);
      alert('Reply sent successfully!');
    } catch {
      alert('Failed to send reply. Please try again.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Mail size={24} />
            Messages from Teachers
            {unreadCount > 0 && (
              <span className="bg-red-500 text-white text-xs py-0.5 px-2 rounded-full font-semibold">
                {unreadCount} new
              </span>
            )}
          </h1>
          <p className="text-muted-foreground text-sm mt-1">
            Stay updated on your children's academic progress
          </p>
        </div>
      </div>

      {/* Student Filter */}
      <div className="card mb-6">
        <div className="flex items-center gap-4 flex-wrap">
          <div className="flex items-center gap-2">
            <GraduationCap size={18} className="text-blue-600" />
            <span className="font-medium text-sm">Filter by child:</span>
          </div>
          <div className="flex gap-2 flex-wrap">
            <button
              onClick={() => setSelectedStudent('all')}
              className={`py-2 px-4 rounded-full border text-sm font-medium transition-all ${
                selectedStudent === 'all' 
                  ? 'bg-blue-600 border-blue-600 text-white' 
                  : 'bg-card border-border text-muted-foreground hover:bg-muted'
              }`}
            >
              All Children
            </button>
            {children.map(child => (
              <button
                key={child.id}
                onClick={() => setSelectedStudent(child.id)}
                className={`py-2 px-4 rounded-full border text-sm font-medium transition-all flex items-center gap-1.5 ${
                  selectedStudent === child.id 
                    ? 'bg-blue-600 border-blue-600 text-white' 
                    : 'bg-card border-border text-muted-foreground hover:bg-muted'
                }`}
              >
                <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[0.7rem] font-bold ${
                  selectedStudent === child.id 
                    ? 'bg-white/30 text-white' 
                    : 'bg-blue-100 dark:bg-blue-950 text-blue-600 dark:text-blue-400'
                }`}>
                  {child.first_name?.[0]}{child.last_name?.[0]}
                </span>
                {child.first_name} {child.last_name?.[0]}.
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Messages List */}
      {loading ? (
        <div className="card text-center p-12 text-muted-foreground">
          Loading messages...
        </div>
      ) : filteredMessages.length === 0 ? (
        <div className="card text-center p-12">
          <Mail size={48} className="mx-auto mb-4 text-text-muted/30" />
          <h3 className="text-text-secondary font-semibold">No messages yet</h3>
          <p className="text-text-muted text-sm mt-2">
            Messages from your children's teachers will appear here
          </p>
        </div>
      ) : (
        <div className="flex flex-col gap-4">
          {filteredMessages.map(msg => (
            <div key={msg.id} className={`card transition-all duration-200 border-l-4 ${msg.is_read ? 'border-l-border' : 'border-l-blue-600'}`}>
              {/* Message Header */}
              <div className={`flex items-start gap-4 ${expandedMsg === msg.id ? 'mb-4' : 'mb-0'}`}>
                <div className="w-12 h-12 rounded-full bg-amber-100 dark:bg-amber-950/30 flex items-center justify-center flex-shrink-0">
                  <User size={24} className="text-amber-800 dark:text-amber-300" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1 flex-wrap">
                    <span className="font-semibold text-text">{msg.teacher_name}</span>
                    <span className="text-text-muted text-xs">•</span>
                    <span className="bg-blue-100 dark:bg-blue-950 text-blue-800 dark:text-blue-400 text-[0.7rem] py-0.5 px-2 rounded-full font-medium">
                      {msg.student_name}
                    </span>
                    <span className="text-text-muted text-xs">•</span>
                    <span className="text-text-muted text-xs">{formatDate(msg.created_at)}</span>
                    {!msg.is_read && (
                      <span className="bg-blue-600 text-white text-[0.65rem] py-0.5 px-1.5 rounded-full font-bold">
                        NEW
                      </span>
                    )}
                  </div>
                  <h3 className="font-semibold text-text mb-1">{msg.subject}</h3>
                  <p className="text-muted-foreground text-sm leading-relaxed">
                    {expandedMsg === msg.id ? msg.body : msg.body.substring(0, 120) + (msg.body.length > 120 ? '...' : '')}
                  </p>
                </div>
              </div>

              {/* Expand/Collapse */}
              <div className="ml-16 mt-3 flex gap-2">
                <button
                  onClick={() => setExpandedMsg(expandedMsg === msg.id ? null : msg.id)}
                  className="flex items-center gap-1.5 py-2 px-3.5 rounded-lg border border-border bg-card text-muted-foreground hover:border-blue-600 hover:text-blue-600 dark:hover:border-blue-500 dark:hover:text-blue-500 text-xs font-medium transition-all cursor-pointer"
                >
                  {expandedMsg === msg.id ? (
                    <> <ChevronUp size={16} /> Show Less</>
                  ) : (
                    <> <ChevronDown size={16} /> Read More</>
                  )}
                </button>

                <button
                  onClick={() => setShowReply(showReply === msg.id ? null : msg.id)}
                  className="flex items-center gap-1.5 py-2 px-3.5 rounded-lg border border-emerald-500 bg-emerald-500 text-white hover:bg-emerald-600 text-xs font-medium transition-all cursor-pointer"
                >
                  <Send size={16} /> Reply
                </button>
              </div>

              {/* Reply Form */}
              {showReply === msg.id && (
                <div className="ml-16 mt-4 p-4 bg-muted/50 rounded-lg">
                  <div className="mb-2 text-xs text-muted-foreground">
                    Replying to <span className="font-semibold">{msg.teacher_name}</span> regarding <span className="font-semibold">{msg.student_name}</span>
                  </div>
                  <textarea
                    value={replyText}
                    onChange={(e) => setReplyText(e.target.value)}
                    placeholder="Type your reply here..."
                    className="w-full min-h-[100px] p-3 rounded-lg border border-border bg-card text-sm resize-y font-sans"
                  />
                  <div className="flex gap-2 mt-3 justify-end">
                    <button
                      onClick={() => { setShowReply(null); setReplyText(''); }}
                      className="flex items-center gap-1.5 py-2 px-4 rounded-lg border border-border bg-card text-muted-foreground hover:bg-muted text-xs font-medium cursor-pointer"
                    >
                      <X size={16} /> Cancel
                    </button>
                    <button
                      onClick={() => handleSendReply(msg.id)}
                      disabled={!replyText.trim() || sending}
                      className={`flex items-center gap-1.5 py-2 px-4 rounded-lg border-none text-white text-xs font-medium transition-all ${
                        replyText.trim() 
                          ? 'bg-emerald-500 hover:bg-emerald-600 cursor-pointer' 
                          : 'bg-emerald-200 dark:bg-emerald-950/30 text-emerald-100/50 cursor-not-allowed'
                      }`}
                    >
                      <Send size={16} /> {sending ? 'Sending...' : 'Send Reply'}
                    </button>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}