import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  FileText, 
  Search, 
  Filter, 
  Download, 
  Printer, 
  Clock, 
  User, 
  Activity, 
  CheckCircle2, 
  ShieldCheck,
  ExternalLink,
  ChevronRight,
  TrendingUp,
  Pill,
  Syringe,
  X,
  Stethoscope
} from 'lucide-react';

interface PCRRecord {
  id: string;
  date: string;
  ambulance: string;
  patient: string;
  age: string;
  gender: string;
  triage: 'RED' | 'YELLOW' | 'GREEN';
  status: 'RECEIVED' | 'PENDING_SIGN';
  emt: string;
  hospitalSign: string | null;
  vitals: { hr: string; spo2: string; bp: string; rr: string };
  meds: string[];
  interventions: string[];
}

const PCR_DETAIL_VIEW = ({ record, onClose }: { record: PCRRecord; onClose: () => void }) => {
  return (
    <motion.div 
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="pcr-modal-overlay"
      onClick={onClose}
    >
      <motion.div 
        initial={{ scale: 0.95, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        exit={{ scale: 0.95, opacity: 0, y: 20 }}
        className="pcr-detail-card"
        onClick={e => e.stopPropagation()}
      >
        <div className="pcr-detail-header">
          <div className="pcr-id-badge">
            <FileText size={18} />
            <span>RECORD {record.id}</span>
          </div>
          <button className="close-pcr-btn" onClick={onClose}><X size={20} /></button>
        </div>

        <div className="pcr-detail-content">
          <section className="pcr-section patient-bio">
            <div className="section-label">PATIENT INFORMATION</div>
            <div className="bio-grid">
              <div className="bio-item"><span className="label">Full Name:</span> <span className="value">{record.patient}</span></div>
              <div className="bio-item"><span className="label">Age/Gender:</span> <span className="value">{record.age} / {record.gender}</span></div>
              <div className="bio-item"><span className="label">Ambulance:</span> <span className="value">{record.ambulance} (ALS)</span></div>
              <div className="bio-item"><span className="label">Lead EMT:</span> <span className="value">{record.emt}</span></div>
            </div>
          </section>

          <div className="pcr-row-split">
            <section className="pcr-section vitals-trends">
              <div className="section-label"><TrendingUp size={14} /> VITAL SIGN TRENDS</div>
              <div className="vitals-trend-grid">
                <div className="trend-item">
                  <span className="label">HR (BPM)</span>
                  <div className="sparkline-placeholder" />
                  <span className="value">{record.vitals.hr}</span>
                </div>
                <div className="trend-item">
                  <span className="label">SpO2 (%)</span>
                  <div className="sparkline-placeholder green" />
                  <span className="value">{record.vitals.spo2}</span>
                </div>
                <div className="trend-item">
                  <span className="label">BP (mmHg)</span>
                  <span className="value">{record.vitals.bp}</span>
                </div>
              </div>
            </section>

            <section className="pcr-section interventions">
              <div className="section-label"><Stethoscope size={14} /> INTERVENTIONS & MEDS</div>
              <div className="med-list">
                {record.meds.map((med, i) => (
                  <div key={i} className="med-item"><Pill size={12} /> {med}</div>
                ))}
                {record.interventions.map((int, i) => (
                  <div key={i} className="med-item highlight"><Activity size={12} /> {int}</div>
                ))}
              </div>
            </section>
          </div>

          <section className="pcr-section hms-integration">
            <div className="section-label">TRANSFER OF CARE & SIGN-OFF</div>
            <div className="sign-off-panel">
              {record.status === 'PENDING_SIGN' ? (
                <div className="pending-sign-area">
                  <p>I verify that the patient and the associated ePCR have been received by the clinical team.</p>
                  <button className="confirm-sign-btn">DIGITALLY SIGN & SYNC TO HMIS</button>
                </div>
              ) : (
                <div className="completed-sign-area">
                  <ShieldCheck size={24} className="text-green-500" />
                  <div>
                    <div className="signed-by">Signed by: {record.hospitalSign}</div>
                    <div className="signed-at">Timestamp: {record.date} (Synced)</div>
                  </div>
                </div>
              )}
            </div>
          </section>
        </div>

        <div className="pcr-detail-footer">
          <button className="pcr-action-btn primary"><Download size={16} /> DOWNLOAD PDF</button>
          <button className="pcr-action-btn"><Printer size={16} /> PRINT RECORD</button>
        </div>
      </motion.div>
    </motion.div>
  );
};

export const EPCRRecords: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedPCR, setSelectedPCR] = useState<PCRRecord | null>(null);

  const records: PCRRecord[] = [
    { 
      id: 'PCR-8821', 
      date: '2026-05-05 12:30', 
      ambulance: 'KA-01-AM-102', 
      patient: 'Rajesh Khanna', 
      age: '45',
      gender: 'M',
      triage: 'RED', 
      status: 'RECEIVED', 
      emt: 'Arjun K.', 
      hospitalSign: 'Dr. Ramesh',
      vitals: { hr: '124', spo2: '88', bp: '100/60', rr: '24' },
      meds: ['Epinephrine 1mg', 'Amiodarone 300mg'],
      interventions: ['CPR Performed', 'Intubation', 'IV Access Established']
    },
    { 
      id: 'PCR-8815', 
      date: '2026-05-05 11:15', 
      ambulance: 'KA-05-MN-88', 
      patient: 'Unknown Male', 
      age: '28',
      gender: 'M',
      triage: 'RED', 
      status: 'PENDING_SIGN', 
      emt: 'Suman R.', 
      hospitalSign: null,
      vitals: { hr: '142', spo2: '82', bp: '80/40', rr: '28' },
      meds: ['Normal Saline 500ml', 'TXA 1g'],
      interventions: ['C-Collar Applied', 'Hemorrhage Control', 'Oxygen (15L)']
    },
    { 
      id: 'PCR-8798', 
      date: '2026-05-04 22:40', 
      ambulance: 'KA-03-KL-44', 
      patient: 'Amit Shah', 
      age: '58',
      gender: 'M',
      triage: 'GREEN', 
      status: 'RECEIVED', 
      emt: 'Kiran P.', 
      hospitalSign: 'Nurse Meera',
      vitals: { hr: '82', spo2: '98', bp: '120/80', rr: '16' },
      meds: [],
      interventions: ['Splinting (Right Leg)']
    },
  ];

  return (
    <motion.div 
      initial={{ opacity: 0, x: 20 }}
      animate={{ opacity: 1, x: 0 }}
      className="module-content"
    >
      <div className="module-header-modern">
        <div className="title-wrap">
          <h3>ePCR RECEIPT & ARCHIVE</h3>
          <div className="live-pill">
            <span className="pulse" /> DIGITAL HANDOVER REPOSITORY
          </div>
        </div>
        <div className="action-area-header">
          <div className="search-mini">
            <Search size={14} />
            <input 
              type="text" 
              placeholder="Search by Patient, MRN, Incident ID..." 
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <button className="register-staff-btn-premium">
            <Filter size={18} />
            <span className="hide-mobile">FILTERS</span>
          </button>
        </div>
      </div>

      <div className="epcr-stats-strip">
        <div className="mini-stat">
          <span className="label">TODAY'S ePCRs</span>
          <span className="value">12</span>
        </div>
        <div className="mini-stat">
          <span className="label">AWAITING SIGNATURE</span>
          <span className="value-alert">01</span>
        </div>
        <div className="mini-stat">
          <span className="label">SYNCED TO HMIS</span>
          <span className="value">11</span>
        </div>
      </div>

      <div className="epcr-table-container">
        <table className="staff-table-premium">
          <thead>
            <tr>
              <th>Record ID & Date</th>
              <th>Ambulance & EMT</th>
              <th>Patient Details</th>
              <th>Triage & Clinical Status</th>
              <th>Handoff Signature</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {records.map(record => (
              <tr key={record.id} className="table-row-hover" onClick={() => setSelectedPCR(record)}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div className="record-icon-mini"><FileText size={14} /></div>
                    <div>
                      <div className="record-id">{record.id}</div>
                      <div className="record-date">{record.date}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <div className="record-meta">
                    <span className="reg-no">{record.ambulance}</span>
                    <span className="emt-name">{record.emt}</span>
                  </div>
                </td>
                <td>
                  <div className="record-patient">{record.patient}</div>
                </td>
                <td>
                  <div className="record-status-wrap">
                    <span className={`triage-tag triage-${record.triage.toLowerCase()}`}>{record.triage}</span>
                    <span className={`receive-status ${record.status.toLowerCase()}`}>
                      {record.status === 'RECEIVED' ? <CheckCircle2 size={12} /> : <Clock size={12} />}
                      {record.status.replace('_', ' ')}
                    </span>
                  </div>
                </td>
                <td>
                  {record.hospitalSign ? (
                    <div className="sign-badge">
                      <ShieldCheck size={12} />
                      {record.hospitalSign}
                    </div>
                  ) : (
                    <button className="sign-action-btn">PENDING SIGN</button>
                  )}
                </td>
                <td>
                  <div className="action-row-mini">
                    <button className="tag-btn" title="View ePCR"><ExternalLink size={14} /></button>
                    <button className="tag-btn" title="Download PDF"><Download size={14} /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <AnimatePresence>
        {selectedPCR && <PCR_DETAIL_VIEW record={selectedPCR} onClose={() => setSelectedPCR(null)} />}
      </AnimatePresence>
    </motion.div>
  );
};
