import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  UserCheck,
  Award,
  CalendarCheck,
  CreditCard,
  MessageSquare,
  AlertTriangle,
  Radio,
  CheckCircle2,
  Lock,
  Unlock,
  Printer,
  ChevronRight,
  TrendingUp,
  Mail,
  Send,
  Building,
  Phone,
  QrCode,
  ShieldCheck,
} from 'lucide-react';
import { StudentIDCardModal } from '../components/StudentIDCardModal';

interface ParentDashboardProps {
  onOpenBankPayment: () => void;
  onOpenReportCard: (studentId: string) => void;
  onOpenMessages: () => void;
}

export const ParentDashboard: React.FC<ParentDashboardProps> = ({
  onOpenBankPayment,
  onOpenReportCard,
  onOpenMessages,
}) => {
  const {
    currentUser,
    grades,
    attendance,
    fees,
    messages,
    sendMessage,
    isResultsLocked,
    courses,
  } = useCollege();

  const childStudentId = currentUser.studentId || 'STC/2026/ICT-108';
  const childFee = fees.find(f => f.studentId === childStudentId) || fees[1];
  const childGrades = grades.filter(g => g.studentId === childStudentId);
  const childAttendance = attendance.filter(a => a.studentId === childStudentId);
  const lockStatus = isResultsLocked(childStudentId);

  // Digital Student ID Modal State
  const [isIdModalOpen, setIsIdModalOpen] = useState(false);

  // Quick message state
  const [quickMsgContent, setQuickMsgContent] = useState('');
  const [msgSentNotice, setMsgSentNotice] = useState(false);

  // Attendance metrics
  const totalSessions = childAttendance.length || 1;
  const presentCount = childAttendance.filter(a => a.status === 'Present').length;
  const lateCount = childAttendance.filter(a => a.status === 'Late').length;
  const absentCount = childAttendance.filter(a => a.status === 'Absent').length;
  const attendanceRate = Math.round(((presentCount + lateCount * 0.7) / totalSessions) * 100) || 88;

  // GPA
  const totalGpa = childGrades.reduce((sum, g) => sum + g.gpa, 0);
  const avgGpa = childGrades.length > 0 ? (totalGpa / childGrades.length).toFixed(2) : '3.80';

  const handleSendQuickMessage = (e: React.FormEvent) => {
    e.preventDefault();
    if (!quickMsgContent) return;

    sendMessage({
      senderId: currentUser.id,
      senderName: currentUser.name,
      senderRole: 'parent',
      receiverId: 'user-teacher-1',
      receiverName: 'Eng. Patrick Chisale',
      receiverRole: 'teacher',
      studentId: childStudentId,
      studentName: childFee ? childFee.studentName : 'Chimwemwe Phiri',
      subject: `Inquiry regarding ${childFee?.studentName || 'Student'}`,
      content: quickMsgContent,
    });

    setQuickMsgContent('');
    setMsgSentNotice(true);
    setTimeout(() => setMsgSentNotice(false), 4000);
  };

  return (
    <div className="space-y-6">
      
      {/* Guardian Header Banner */}
      <div className="bg-slate-900 text-white rounded-2xl p-6 shadow-md border border-slate-800 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-full bg-purple-600 border-2 border-purple-400 flex items-center justify-center font-bold text-white text-xl">
            <UserCheck className="w-7 h-7" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="bg-purple-600 text-white font-mono text-[10px] font-bold px-2 py-0.5 rounded">
                Parent & Guardian Portal
              </span>
              <span className="text-xs text-slate-400">Linked Student: {childFee?.studentName || 'Chimwemwe Phiri'}</span>
            </div>
            <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white">{currentUser.name}</h1>
            <p className="text-xs text-slate-300">
              Real-time academic monitoring, automated attendance push alerts, and direct faculty communication.
            </p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2.5">
          <button
            onClick={() => setIsIdModalOpen(true)}
            className="px-4 py-2 bg-purple-500 hover:bg-purple-400 text-white text-xs font-bold rounded-lg transition shadow flex items-center gap-1.5"
          >
            <QrCode className="w-4 h-4" />
            Student ID & QR Pass
          </button>

          <button
            onClick={onOpenBankPayment}
            className="px-4 py-2 bg-amber-500 hover:bg-amber-600 text-slate-950 text-xs font-bold rounded-lg transition shadow flex items-center gap-1.5"
          >
            <CreditCard className="w-4 h-4" />
            Settle Fees (National Bank)
          </button>
          
          <button
            onClick={() => onOpenReportCard(childStudentId)}
            className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold rounded-lg transition shadow flex items-center gap-1.5"
          >
            <Award className="w-4 h-4" />
            Official Report Card
          </button>
        </div>
      </div>

      {/* Snapshot Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Real-time Attendance</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{attendanceRate}%</span>
            <span className={`text-[10px] px-2 py-0.5 rounded font-bold ${
              attendanceRate >= 75 ? 'bg-emerald-100 text-emerald-800' : 'bg-rose-100 text-rose-800'
            }`}>
              {absentCount > 0 ? `${absentCount} Absence Logged` : 'Perfect'}
            </span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Academic Progress</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">
              {lockStatus.isLocked ? 'Restricted' : `${avgGpa} GPA`}
            </span>
            <span className="text-[10px] text-blue-700 bg-blue-100 px-2 py-0.5 rounded font-bold">
              {lockStatus.isLocked ? 'Clearance Required' : 'Distinction'}
            </span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Fee Account</span>
          <div className="flex items-baseline justify-between">
            <span className={`text-base font-bold font-mono ${lockStatus.isLocked ? 'text-rose-600' : 'text-emerald-700'}`}>
              MK {lockStatus.balanceDue.toLocaleString()}
            </span>
            <span className="text-[10px] text-slate-500 font-mono">
              {lockStatus.isLocked ? '30% Balance' : '100% Cleared'}
            </span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs space-y-1">
          <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider block">Direct Messaging</span>
          <div className="flex items-baseline justify-between">
            <span className="text-2xl font-bold font-mono text-slate-900">{messages.length}</span>
            <span className="text-[10px] text-purple-700 bg-purple-100 px-2 py-0.5 rounded font-bold">
              Lecturer Active
            </span>
          </div>
        </div>
      </div>

      {/* SECTION 1: ATTENDANCE TRACKING & AUTOMATED ALERT FEED */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-4">
        <div className="flex items-center justify-between border-b border-slate-200 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-amber-100 flex items-center justify-center text-amber-800">
              <Radio className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-base font-bold text-slate-900">
                Attendance Radar & Absence Notifications
              </h2>
              <p className="text-xs text-slate-500">
                Automated SMS & push notifications triggered on class absence or late arrival
              </p>
            </div>
          </div>
        </div>

        {absentCount > 0 && (
          <div className="p-4 bg-rose-50 border border-rose-300 rounded-xl text-xs text-rose-950 flex items-start gap-3">
            <AlertTriangle className="w-5 h-5 text-rose-600 shrink-0 mt-0.5" />
            <div className="space-y-1">
              <strong className="block text-rose-900">
                Absence Alert Dispatched on 20 Aug 2026:
              </strong>
              <p>
                Chimwemwe was marked absent during the Hardware Diagnostics Workshop by Eng. Patrick Chisale. Automated guardian notice was dispatched to {currentUser.email}.
              </p>
            </div>
          </div>
        )}

        <div className="border border-slate-200 rounded-xl overflow-hidden text-xs">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-100 text-slate-700 font-semibold border-b border-slate-200">
                <th className="p-3">Date</th>
                <th className="p-3">Session Topic / Workshop</th>
                <th className="p-3">Lecturer</th>
                <th className="p-3">Status</th>
                <th className="p-3">Guardian Notice</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {childAttendance.map(att => (
                <tr key={att.id} className="hover:bg-slate-50">
                  <td className="p-3 font-mono text-slate-900">{att.date}</td>
                  <td className="p-3 font-medium text-slate-800">
                    {att.sessionName}
                    {att.remarks && <span className="text-[10px] text-slate-500 block">{att.remarks}</span>}
                  </td>
                  <td className="p-3 text-slate-600">{att.markedBy}</td>
                  <td className="p-3">
                    <span className={`px-2.5 py-0.5 rounded text-[10px] font-bold ${
                      att.status === 'Present'
                        ? 'bg-emerald-100 text-emerald-900'
                        : att.status === 'Late'
                        ? 'bg-amber-100 text-amber-900'
                        : 'bg-rose-100 text-rose-900'
                    }`}>
                      {att.status}
                    </span>
                  </td>
                  <td className="p-3 text-slate-500 font-mono text-[10px]">
                    {att.status === 'Absent' ? 'Dispatched via Push/SMS' : 'Normal Log'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* SECTION 2: ACADEMIC PERFORMANCE (FEE RESTRICTED) */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-4">
        <div className="flex items-center justify-between border-b border-slate-200 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center text-emerald-800">
              <Award className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-base font-bold text-slate-900">
                Child Academic Progress Reports & Exam Marks
              </h2>
              <p className="text-xs text-slate-500">
                Official marks and continuous assessment performance
              </p>
            </div>
          </div>

          <button
            onClick={() => onOpenReportCard(childStudentId)}
            className="px-3.5 py-1.5 bg-slate-900 hover:bg-slate-800 text-white rounded-lg text-xs font-semibold flex items-center gap-1.5"
          >
            <Printer className="w-3.5 h-3.5 text-emerald-400" />
            Print Report Card
          </button>
        </div>

        {lockStatus.isLocked ? (
          <div className="bg-amber-50 border border-amber-300 rounded-xl p-5 text-center space-y-3">
            <div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center mx-auto text-amber-700">
              <Lock className="w-5 h-5" />
            </div>
            <div className="max-w-md mx-auto text-xs space-y-1">
              <strong className="text-amber-950 font-bold block text-sm">
                Exam Marks Locked Pending MK {lockStatus.balanceDue.toLocaleString()} Tuition Balance
              </strong>
              <p className="text-slate-600">
                Please deposit the outstanding balance into National Bank Customs Road Account <strong>1003452219</strong> to view full exam transcripts.
              </p>
            </div>
            <button
              onClick={onOpenBankPayment}
              className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs"
            >
              Upload Bank Deposit Slip
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {childGrades.map(grd => (
              <div key={grd.id} className="p-4 rounded-xl border border-slate-200 bg-slate-50 space-y-2 text-xs">
                <div className="flex justify-between items-start">
                  <div>
                    <h4 className="font-bold text-slate-900 text-sm">{grd.subjectName}</h4>
                    <span className="text-[10px] text-slate-500 font-mono">{grd.examBoard}</span>
                  </div>
                  <span className="px-2.5 py-1 bg-emerald-100 text-emerald-900 font-bold rounded text-xs">
                    Grade {grd.letterGrade} ({grd.totalScore}%)
                  </span>
                </div>
                <p className="text-slate-600 italic">"{grd.remarks}"</p>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* SECTION 3: DIRECT PARENT-TEACHER MESSAGING */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs p-6 space-y-4">
        <div className="flex items-center justify-between border-b border-slate-200 pb-3">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-purple-100 flex items-center justify-center text-purple-800">
              <MessageSquare className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-base font-bold text-slate-900">
                Direct Communication with Lecturers & Accounts
              </h2>
              <p className="text-xs text-slate-500">
                Chat directly with Eng. Patrick Chisale and Mr. T. Mweghama (Accounts)
              </p>
            </div>
          </div>

          <button
            onClick={onOpenMessages}
            className="text-xs font-semibold text-emerald-700 hover:text-emerald-900 flex items-center gap-1"
          >
            Open Full Inbox
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>

        {msgSentNotice && (
          <div className="p-3 bg-emerald-50 border border-emerald-300 rounded-xl text-xs font-medium text-emerald-900 flex items-center gap-2">
            <CheckCircle2 className="w-4 h-4 text-emerald-600" />
            Message sent directly to Eng. Patrick Chisale.
          </div>
        )}

        {/* Recent Message Threads */}
        <div className="space-y-3">
          {messages.map(msg => (
            <div
              key={msg.id}
              className="border border-slate-200 rounded-xl p-4 bg-slate-50/70 space-y-2 text-xs"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className="font-bold text-slate-900">{msg.senderName}</span>
                  <span className="text-[10px] bg-slate-200 px-2 py-0.5 rounded text-slate-700 font-semibold uppercase">
                    {msg.senderRole}
                  </span>
                </div>
                <span className="text-slate-400 text-[10px]">{msg.timestamp}</span>
              </div>
              <p className="font-semibold text-slate-800 text-[11px]">{msg.subject}</p>
              <p className="text-slate-600 leading-relaxed">{msg.content}</p>
            </div>
          ))}
        </div>

        {/* Quick reply composer */}
        <form onSubmit={handleSendQuickMessage} className="pt-2 flex gap-2">
          <input
            type="text"
            placeholder="Type a message or inquiry to Eng. Patrick Chisale..."
            value={quickMsgContent}
            onChange={e => setQuickMsgContent(e.target.value)}
            className="flex-1 px-3 py-2 border border-slate-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-emerald-500"
          />
          <button
            type="submit"
            className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs flex items-center gap-1.5 shadow-sm"
          >
            <Send className="w-3.5 h-3.5" />
            Send
          </button>
        </form>
      </div>

      {/* DIGITAL STUDENT ID MODAL FOR WARD */}
      <StudentIDCardModal
        isOpen={isIdModalOpen}
        onClose={() => setIsIdModalOpen(false)}
        user={{
          id: 'student-ward',
          name: childFee?.studentName || 'Chimwemwe Phiri',
          email: 'c.phiri@student.sochetech.org',
          role: 'student',
          studentId: childStudentId,
          avatarUrl: 'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=400&auto=format&fit=crop&q=80',
          title: childFee?.courseName || 'ICT - Systems Support',
        }}
        studentFee={childFee}
      />

    </div>
  );
};
