import React from 'react';
import { motion } from 'framer-motion';
import {
  Building2,
  Users,
  LayoutDashboard,
  Stethoscope,
  Search,
  Plus,
  Edit2,
  Phone,
  Settings,
  MoreVertical,
  Activity
} from 'lucide-react';
import { Card } from '../../components/Common';

interface SetupPanelProps {
  setupSubTab: string;
  onSubTabChange: (tab: string) => void;
  selectedHospital: any;
  setSelectedHospital: (h: any) => void;
  departments: any[];
  setDepartments: (d: any[]) => void;
  allUsers: any[];
  onSaveProfile: () => void;
  onOpenStaffModal: () => void;
  onEditStaff: (user: any) => void;
  onOpenDeptModal: () => void;
}

export const SetupPanel: React.FC<SetupPanelProps> = ({
  setupSubTab,
  onSubTabChange,
  selectedHospital,
  setSelectedHospital,
  departments,
  setDepartments,
  allUsers,
  onSaveProfile,
  onOpenStaffModal,
  onEditStaff,
  onOpenDeptModal,
}) => {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.99 }}
      animate={{ opacity: 1, scale: 1 }}
      className="module-content"
    >
      <div className="setup-layout">
        <aside className="setup-nav">
          <button
            className={`setup-nav-item ${
              setupSubTab === 'PROFILE' ? 'active' : ''
            }`}
            onClick={() => onSubTabChange('PROFILE')}
          >
            <Building2 size={14} /> <span>Profile</span>
          </button>
          <button
            className={`setup-nav-item ${
              setupSubTab === 'USERS' ? 'active' : ''
            }`}
            onClick={() => onSubTabChange('USERS')}
          >
            <Users size={14} /> <span>Users</span>
          </button>
          <button
            className={`setup-nav-item ${
              setupSubTab === 'DEPTS' ? 'active' : ''
            }`}
            onClick={() => onSubTabChange('DEPTS')}
          >
            <LayoutDashboard size={14} /> <span>Departments</span>
          </button>
          <button
            className={`setup-nav-item ${
              setupSubTab === 'BEDS' ? 'active' : ''
            }`}
            onClick={() => onSubTabChange('BEDS')}
          >
            <Stethoscope size={14} /> <span>Bed Management</span>
          </button>
        </aside>

        <div className="setup-content-modern no-scrollbar">
          {setupSubTab === 'PROFILE' && (
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              style={{ display: 'block' }}
            >
              <Card title="Hospital Profile & Configuration">
                <div className="setup-form-modern" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
                  <div className="form-group-premium" style={{ gridColumn: '1 / -1' }}>
                    <label>Institution Name</label>
                    <input
                      type="text"
                      className="setup-input-premium"
                      value={selectedHospital?.name || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          name: e.target.value,
                        })
                      }
                    />
                  </div>
                  <div className="form-group-premium" style={{ gridColumn: '1 / -1' }}>
                    <label>Physical Address</label>
                    <input
                      type="text"
                      className="setup-input-premium"
                      value={selectedHospital?.address || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          address: e.target.value,
                        })
                      }
                    />
                  </div>
                  
                  <div className="form-group-premium">
                    <label>Emergency Phone</label>
                    <input
                      type="text"
                      className="setup-input-premium"
                      value={selectedHospital?.emergency_phone || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          emergency_phone: e.target.value,
                        })
                      }
                    />
                  </div>
                  <div className="form-group-premium">
                    <label>Contact Phone</label>
                    <input
                      type="text"
                      className="setup-input-premium"
                      value={selectedHospital?.contact_phone || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          contact_phone: e.target.value,
                        })
                      }
                    />
                  </div>

                  <div className="form-group-premium" style={{ gridColumn: '1 / -1' }}>
                    <label>Contact Email</label>
                    <input
                      type="email"
                      className="setup-input-premium"
                      value={selectedHospital?.contact_email || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          contact_email: e.target.value,
                        })
                      }
                    />
                  </div>
                  
                  <div className="form-group-premium">
                    <label>GPS Latitude</label>
                    <input
                      type="number"
                      className="setup-input-premium"
                      value={selectedHospital?.gps_lat || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          gps_lat: e.target.value,
                        })
                      }
                    />
                  </div>
                  <div className="form-group-premium">
                    <label>GPS Longitude</label>
                    <input
                      type="number"
                      className="setup-input-premium"
                      value={selectedHospital?.gps_lon || ''}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          gps_lon: e.target.value,
                        })
                      }
                    />
                  </div>
                  
                  <div className="form-group-premium" style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 0' }}>
                    <input
                      type="checkbox"
                      id="nabh_status"
                      checked={selectedHospital?.nabh_status || false}
                      onChange={(e) =>
                        setSelectedHospital({
                          ...selectedHospital,
                          nabh_status: e.target.checked,
                        })
                      }
                      style={{ width: '18px', height: '18px', cursor: 'pointer' }}
                    />
                    <label htmlFor="nabh_status" style={{ margin: 0, cursor: 'pointer', fontSize: '1rem', fontWeight: 'bold' }}>NABH Accredited Institution</label>
                  </div>

                  <div style={{ gridColumn: '1 / -1', marginTop: '16px' }}>
                    <button
                      className="setup-confirm-btn"
                      onClick={onSaveProfile}
                    >
                      Save Configuration
                    </button>
                  </div>
                </div>
              </Card>
            </motion.div>
          )}

          {setupSubTab === 'USERS' && (
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
            >
              <Card title="Personnel Registry">
                <div className="setup-actions-bar">
                  <div className="search-mini">
                    <Search size={16} />
                    <input
                      type="text"
                      placeholder="Filter by name or role..."
                    />
                  </div>
                  <button
                    className="register-staff-btn-premium"
                    onClick={onOpenStaffModal}
                  >
                    <Plus size={16} /> Add New Staff
                  </button>
                </div>
                <table className="staff-table-premium">
                  <thead>
                    <tr>
                      <th>Operator Name</th>
                      <th>Designation</th>
                      <th>Node Alignment</th>
                      <th>Auth Status</th>
                      <th style={{ textAlign: 'right' }}>Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {allUsers
                      .filter(
                        (u) =>
                          u.hospitalId ===
                            selectedHospital?.rawUser?.hospitalId ||
                          u.organisationId ===
                            selectedHospital?.rawUser?.organisationId
                      )
                      .map((u, i) => (
                        <tr key={i}>
                          <td style={{ fontWeight: 800 }}>
                            {u.name || u.username}
                          </td>
                          <td>
                            <span
                              className="v-status IDLE"
                              style={{ fontSize: '0.6rem' }}
                            >
                              {u.roles[0]?.replace('_', ' ')}
                            </span>
                          </td>
                          <td style={{ opacity: 0.7 }}>
                            {selectedHospital?.name}
                          </td>
                          <td>
                            <span className="node-status-text ON">
                              AUTHORIZED
                            </span>
                          </td>
                          <td style={{ textAlign: 'right' }}>
                            <button
                              className="btn-icon"
                              onClick={() => onEditStaff(u)}
                              style={{ background: 'transparent', border: 'none', color: 'var(--accent-cyan)', cursor: 'pointer' }}
                              title="Edit Staff"
                            >
                              <Edit2 size={16} />
                            </button>
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </Card>
            </motion.div>
          )}

          {setupSubTab === 'DEPTS' && (
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
            >
              <Card title="Emergency Departments Node Registry">
                <div className="setup-actions-bar">
                  <div className="search-mini">
                    <Search size={16} />
                    <input type="text" placeholder="Search departments..." />
                  </div>
                  <button
                    className="register-staff-btn-premium"
                    onClick={onOpenDeptModal}
                  >
                    <Plus size={16} /> ADD DEPARTMENT
                  </button>
                </div>

                <div className="table-responsive-premium">
                  <table className="staff-table-premium">
                    <thead>
                      <tr>
                        <th>Department / Clinical Node</th>
                        <th>Leadership</th>
                        <th>Resource Allocation</th>
                        <th>Communication</th>
                        <th>Ops Status</th>
                        <th style={{ textAlign: 'right' }}>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {departments.map((d, i) => {
                        const occupancy = ((d.occupiedBeds || 0) / (d.totalBedsCapacity || 1)) * 100;
                        const isHighOccupancy = occupancy > 85;
                        
                        return (
                          <motion.tr 
                            key={i}
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: i * 0.05 }}
                          >
                            <td style={{ fontWeight: 800 }}>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                <div style={{ 
                                  width: '36px', 
                                  height: '36px', 
                                  background: 'var(--accent-cyan-soft)', 
                                  borderRadius: '10px',
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                  color: 'var(--accent-cyan)'
                                }}>
                                  <Activity size={18} />
                                </div>
                                <div>
                                  <div style={{ fontSize: '0.95rem', color: '#1e293b' }}>{d.name}</div>
                                  <div style={{ fontSize: '0.65rem', color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Node: {d.id?.substring(0, 8)}</div>
                                </div>
                              </div>
                            </td>
                            <td>
                              <div style={{ display: 'flex', flexDirection: 'column' }}>
                                <span style={{ fontWeight: 700, fontSize: '0.85rem' }}>{d.headOfDepartment}</span>
                                <span style={{ fontSize: '0.7rem', color: '#94a3b8' }}>Chief of Medicine</span>
                              </div>
                            </td>
                            <td>
                              <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', minWidth: '140px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.75rem', fontWeight: 700 }}>
                                  <span style={{ color: isHighOccupancy ? '#ef4444' : '#64748b' }}>{d.occupiedBeds}/{d.totalBedsCapacity} Units</span>
                                  <span style={{ color: '#94a3b8' }}>{Math.round(occupancy)}%</span>
                                </div>
                                <div style={{ height: '6px', width: '100%', background: '#f1f5f9', borderRadius: '3px', overflow: 'hidden' }}>
                                  <div style={{ 
                                    height: '100%', 
                                    width: `${occupancy}%`, 
                                    background: isHighOccupancy ? '#ef4444' : 'var(--accent-cyan)',
                                    borderRadius: '3px'
                                  }} />
                                </div>
                                <div style={{ fontSize: '0.65rem', color: '#10b981', fontWeight: 600 }}>{d.availableBeds} Units Available</div>
                              </div>
                            </td>
                            <td>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: '#475569', fontSize: '0.85rem' }}>
                                <Phone size={14} style={{ color: '#94a3b8' }} />
                                {d.contactPhone || 'No direct line'}
                              </div>
                            </td>
                            <td>
                              <span className={`node-status-text ${d.isActive ? 'ON' : 'OFF'}`} style={{ padding: '4px 10px', borderRadius: '20px', fontSize: '0.65rem', display: 'inline-flex', alignItems: 'center', gap: '6px' }}>
                                <div style={{ width: 6, height: 6, borderRadius: '50%', background: d.isActive ? '#10b981' : '#94a3b8' }} />
                                {d.isActive ? 'OPERATIONAL' : 'INACTIVE'}
                              </span>
                            </td>
                            <td style={{ textAlign: 'right' }}>
                              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
                                <button
                                  className={`toggle-btn-modern ${d.isActive ? 'disable' : 'enable'}`}
                                  style={{ padding: '6px 12px', fontSize: '0.65rem', height: '30px' }}
                                  onClick={() => {
                                    const n = [...departments];
                                    n[i].isActive = !n[i].isActive;
                                    setDepartments(n);
                                  }}
                                >
                                  {d.isActive ? 'OFFLINE' : 'ONLINE'}
                                </button>
                                <button className="btn-icon" style={{ background: '#f8fafc', borderRadius: '8px', padding: '6px' }}>
                                  <Settings size={14} color="#64748b" />
                                </button>
                              </div>
                            </td>
                          </motion.tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </Card>
            </motion.div>
          )}

          {setupSubTab === 'BEDS' && (
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
            >
              <Card title="Inventory &amp; Capacity Management">
                <div className="setup-actions-bar">
                  <p
                    style={{
                      margin: 0,
                      color: 'var(--text-secondary)',
                      fontWeight: 600,
                    }}
                  >
                    Active Care Units: {departments.length}
                  </p>
                  <button className="register-staff-btn-premium">
                    <Plus size={16} /> ADD UNIT
                  </button>
                </div>
                <table className="staff-table-premium">
                  <thead>
                    <tr>
                      <th>Care Unit / Dept</th>
                      <th>Total Capacity</th>
                      <th>Occupied</th>
                      <th>Availability</th>
                    </tr>
                  </thead>
                  <tbody>
                    {departments.map((b, i) => {
                      const occ = b.occupiedBeds || 0;
                      const tot = b.totalBedsCapacity || 1;
                      return (
                        <tr key={i}>
                          <td style={{ fontWeight: 800 }}>{b.name}</td>
                          <td>{b.totalBedsCapacity} Units</td>
                          <td
                            style={{
                              color: 'var(--accent-cyan)',
                              fontWeight: 700,
                            }}
                          >
                            {occ}
                          </td>
                          <td>
                            <div
                              className="bed-progress"
                              style={{ width: '100px', marginBottom: 0 }}
                            >
                              <div
                                className="progress-fill"
                                style={{
                                  width: `${(occ / tot) * 100}%`,
                                }}
                              />
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </Card>
            </motion.div>
          )}
        </div>
      </div>
    </motion.div>
  );
};
