import { useState } from 'react';
import { Link } from 'react-router-dom';
import {
  ClipboardCheck,
  RotateCcw,
} from 'lucide-react';

// Simplified components
const BackButton = ({ to, label }: { to: string; label: string }) => (
  <Link to={to} className="flex items-center gap-3 p-4 bg-card border border-border rounded-xl hover:border-primary/50 transition-colors">
    <AlertTriangle className="w-5 h-5" />
    <span>{label}</span>
  </Link>
);

const AlertTriangle = () => <span>⚠️</span>;

// Mock Badge component
const Badge = ({ variant, children }: { variant: string; children: React.ReactNode }) => (
  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${variant === 'default' ? 'bg-muted text-muted-foreground' : ''}`}>
    {children}
  </span>
);

// Mock data for material checklists
interface ChecklistItem {
  id: string;
  name: string;
  checked?: boolean;
}

interface ChecklistSection {
  id: string;
  title: string;
  items: ChecklistItem[];
}

interface MaterialChecklist {
  id: string;
  title: string;
  shortTitle: string;
  phase: string; // inicio_turno, pre_escena, post_servicio
  sections: ChecklistSection[];
}

// Mock material checklists (simplified)
const mockMaterialChecklists: MaterialChecklist[] = [
  {
    id: 'inicio-turno-basico',
    title: 'Checklist de Inicio de Turno - Básico',
    shortTitle: 'Inicio Turno',
    phase: 'inicio_turno',
    sections: [
      {
        id: 'equipo-personal',
        title: 'Equipo Personal',
        items: [
          { id: '1', name: 'Uniforme completo y limpio', checked: false },
          { id: '2', name: 'Identificación visible', checked: false },
          { id: '3', name: 'Calzado adecuado', checked: false },
          { id: '4', name: 'Reloj con segundero', checked: false },
          { id: '5', name: 'Bolígrafos y cuaderno', checked: false },
        ]
      },
      {
        id: 'equipo-proteccion',
        title: 'Equipo de Protección Personal',
        items: [
          { id: '6', name: 'Guantes de nitrilo (talla adecuada)', checked: false },
          { id: '7', name: 'Mascarilla facial', checked: false },
          { id: '8', name: 'Protección ocular', checked: false },
          { id: '9', name: 'Bata o sobretodo impermeable', checked: false },
          { id: '10', name: 'Protección auditiva (si aplica)', checked: false },
        ]
      },
    ]
  },
  {
    id: 'pre-escena-esencial',
    title: 'Checklist Pre-Escena - Esencial',
    shortTitle: 'Pre-Escena',
    phase: 'pre_escena',
    sections: [
      {
        id: 'equipo-vital',
        title: 'Equipo Vital para Emergencia',
        items: [
          { id: '11', name: 'Desfibrilador externo automático (DEA)', checked: false },
          { id: '12', name: 'Kit de vía aérea básica', checked: false },
          { id: '13', name: 'Equipo de inmovilización básica', checked: false },
          { id: '14', name: 'Equino de curación y vendaje', checked: false },
          { id: '15', name: 'Equipo de parto de emergencia', checked: false },
        ]
      },
      {
        id: 'medicamentos-basicos',
        title: 'Medicamentos Básicos',
        items: [
          { id: '16', name: 'Adrenalina 1mg/10ml', checked: false },
          { id: '17', name: 'Salbutamol nebulizador', checked: false },
          { id: '18', name: 'Solución salina 0.9%', checked: false },
          { id: '19', name: 'Glucosa oral', checked: false },
          { id: '20', name: 'Ácido tranexámico', checked: false },
        ]
      },
    ]
  },
  {
    id: 'post-servicio-completo',
    title: 'Checklist Post-Servicio - Completo',
    shortTitle: 'Post-Servicio',
    phase: 'post_servicio',
    sections: [
      {
        id: 'limpieza-desinfeccion',
        title: 'Limpieza y Desinfección',
        items: [
          { id: '21', name: 'Desinfectar superficie de camilla', checked: false },
          { id: '22', name: 'Limpiar y desinfectar equipos usados', checked: false },
          { id: '23', name: 'Reponer materiales consumidos', checked: false },
          { id: '24', name: 'Verificar fecha de caducidad de medicamentos', checked: false },
          { id: '25', name: 'Documentar incidentes o anomalías', checked: false },
        ]
      },
      {
        id: 'reposicion-material',
        title: 'Reposición de Material',
        items: [
          { id: '26', name: 'Reposición de guantes de nitrilo', checked: false },
          { id: '27', name: 'Reposición de apósitos estériles', checked: false },
          { id: '28', name: 'Reposición de apósitos adhesivos', checked: false },
          { id: '29', name: 'Reposición de vendajes elásticos', checked: false },
          { id: '30', name: 'Reposición de solución salina', checked: false },
        ]
      },
    ]
  },
];

// Mock MaterialChecklistViewer component
const MaterialChecklistViewer = ({ checklist, onReset }: { checklist: MaterialChecklist; onReset: () => void }) => (
  <div className="space-y-6">
    <button onClick={onReset} className="mb-4 text-sm text-muted-foreground hover:text-foreground flex items-center gap-2">
      ← Volver a lista de checklists
    </button>
    
    <div className="bg-card border border-border rounded-lg p-6">
      <h2 className="text-xl font-semibold text-foreground mb-4">{checklist.title}</h2>
      <p className="text-muted-foreground">
        {checklist.shortTitle} • {checklist.phase}
      </p>
      
      <div className="space-y-4">
        {checklist.sections.map((section, sectionIndex) => (
          <div key={section.id} className="space-y-4">
            <h3 className="font-semibold text-foreground mb-2">{section.title}</h3>
            <div className="space-y-2">
              {section.items.map((item, itemIndex) => (
                <div key={item.id} className="flex items-center gap-3 p-2 bg-muted/50 rounded mb-1">
                  <input
                    type="checkbox"
                    checked={item.checked}
                    onChange={(e) => {
                      // In a real app, we would update the state here
                      console.log(`Checkbox ${item.id} changed to ${e.target.checked}`);
                    }}
                    className="h-4 w-4 text-primary"
                  />
                  <span className="flex-1">{item.name}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

const Material = () => {
  const [selectedChecklist, setSelectedChecklist] = useState<MaterialChecklist | null>(null);
  const [selectedPhase, setSelectedPhase] = useState<string | 'todos'>('todos');

  const filteredChecklists = selectedPhase === 'todos'
    ? mockMaterialChecklists
    : mockMaterialChecklists.filter(checklist => checklist.phase === selectedPhase);

  return (
    <div className="space-y-6">
      <BackButton to="/" label="Volver al inicio" />

      {/* Header */}
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <ClipboardCheck className="w-8 h-8 text-primary" />
          <div>
            <h1 className="text-3xl font-bold text-foreground">Checklists de Material</h1>
            <p className="text-muted-foreground text-sm">
              Verificación de material sanitario y oxigenoterapia
            </p>
          </div>
        </div>
      </div>

      {!selectedChecklist ? (
        <>
          {/* Phase Filter */}
          <div className="space-y-2">
            <p className="text-xs text-muted-foreground mb-1 uppercase tracking-wide">Fase</p>
            <div className="flex gap-2 overflow-x-auto scrollbar-hide -mx-2 px-2">
              <button
                onClick={() => setSelectedPhase('todos')}
                className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                  selectedPhase === 'todos'
                    ? 'bg-primary text-primary-foreground'
                    : 'bg-muted text-muted-foreground hover:bg-accent'
                }`}
              >
                Todos
              </button>
              {['inicio_turno', 'pre_escena', 'post_servicio'].map((phase) => (
                <button
                  key={phase}
                  onClick={() => setSelectedPhase(phase)}
                  className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                    selectedPhase === phase
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted text-muted-foreground hover:bg-accent'
                  }`}
                >
                  {phase === 'inicio_turno' ? 'Inicio de Turno' :
                   phase === 'pre_escena' ? 'Pre-Escena' : 'Post-Servicio'}
                </button>
              ))}
            </div>
          </div>

          {/* Checklists List */}
          <div className="space-y-4">
            {filteredChecklists.length === 0 ? (
              <div className="text-center py-4">
                <p className="text-muted-foreground">No hay checklists que coincidan con los filtros seleccionados.</p>
              </div>
            ) : (
              <>
                {filteredChecklists.map((checklist) => (
                  <button
                    key={checklist.id}
                    onClick={() => setSelectedChecklist(checklist)}
                    className="w-full text-left card-procedure hover:bg-accent transition-colors"
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <ClipboardCheck className="w-5 h-5 text-primary" />
                          <h3 className="font-semibold text-foreground">{checklist.shortTitle}</h3>
                          <Badge variant="default">{checklist.phase}</Badge>
                        </div>
                        <p className="text-muted-foreground text-sm">
                          {checklist.phase}
                        </p>
                        <p className="text-muted-foreground text-xs mt-1">
                          {checklist.sections.length} sección(es) • {' '}
                          {checklist.sections.reduce((acc, s) => acc + s.items.length, 0)} items
                        </p>
                      </div>
                    </div>
                  </button>
                ))}
              </>
            )}
          </div>
        </>
      ) : (
        <div>
          <MaterialChecklistViewer
            checklist={selectedChecklist}
            onReset={() => setSelectedChecklist(null)}
          />
        </div>
      )}
    </div>
  );
};

export default Material;