import { useState } from 'react';
import { AlertTriangle, CheckCircle, ChevronDown, ChevronUp, Heart, Shield } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import { Button } from '@/components/ui/button';
import { StatePanel } from '@/components/ui/state-panel';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';

type SafetyProtocolIconId = 'fire' | 'shield' | 'heart';

interface SafetyProtocol {
  readonly id: string;
  readonly title: string;
  readonly iconId: SafetyProtocolIconId;
  readonly color: string;
  readonly steps: readonly string[];
  readonly autismConsiderations: readonly string[];
}

const SAFETY_PROTOCOL_ICONS: Record<SafetyProtocolIconId, LucideIcon> = {
  fire: AlertTriangle,
  shield: Shield,
  heart: Heart,
};

export function SafetyProtocolsModule() {
  const protocolsQuery = useContentCatalogPayload<readonly SafetyProtocol[]>(
    CONTENT_CATALOG_TYPES.safetyProtocols,
    [],
  );
  const [expandedProtocol, setExpandedProtocol] = useState<string | null>('fire');
  const [acknowledged, setAcknowledged] = useState<Set<string>>(new Set());
  const protocols = protocolsQuery.payload;
  const errorMessage = getOptionalErrorMessage(protocolsQuery.error);

  const toggleAck = (id: string) => {
    const next = new Set(acknowledged);
    if (next.has(id)) next.delete(id); else next.add(id);
    setAcknowledged(next);
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-red-400 to-red-600 flex items-center justify-center"><AlertTriangle size={20} className="text-white" /></div>
          Safety Protocols
        </h2>
        <p className="text-sm text-gray-500 mt-1">Clear, visual safety standards - always accessible, always current</p>
      </div>
      <div className="space-y-4">
        {protocolsQuery.isLoading && (
          <StatePanel tone="red" alignment="center" loading>
            Loading safety protocols...
          </StatePanel>
        )}
        {errorMessage && (
          <StatePanel tone="red" role="alert">
            {errorMessage}
          </StatePanel>
        )}
        {!protocolsQuery.isLoading && !errorMessage && protocols.length === 0 && (
          <StatePanel>
            No safety protocols are published yet.
          </StatePanel>
        )}
        {!protocolsQuery.isLoading && !errorMessage && protocols.map((protocol) => {
          const ProtocolIcon = SAFETY_PROTOCOL_ICONS[protocol.iconId];

          return (
            <div key={protocol.id} className="bg-white rounded-2xl border border-violet-100 shadow-sm overflow-hidden">
              <Button type="button" onClick={() => setExpandedProtocol(expandedProtocol === protocol.id ? null : protocol.id)} className="w-full h-auto px-5 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors bg-transparent text-inherit">
                <div className="flex items-center gap-3">
                  <div className={`w-10 h-10 rounded-xl bg-gradient-to-br ${protocol.color} flex items-center justify-center text-white`}>
                    <ProtocolIcon size={20} />
                  </div>
                  <div className="text-left"><h3 className="font-semibold text-gray-800">{protocol.title}</h3><p className="text-xs text-gray-400">{protocol.steps.length} steps - {protocol.autismConsiderations.length} autism considerations</p></div>
                </div>
                <div className="flex items-center gap-3">
                  {acknowledged.has(protocol.id) && <span className="px-2.5 py-1 bg-emerald-100 text-emerald-700 rounded-lg text-[10px] font-semibold">ACKNOWLEDGED</span>}
                  {expandedProtocol === protocol.id ? <ChevronUp size={18} className="text-gray-400" /> : <ChevronDown size={18} className="text-gray-400" />}
                </div>
              </Button>
              {expandedProtocol === protocol.id && (
                <div className="px-5 pb-5 space-y-4">
                  <div><h4 className="font-semibold text-sm text-gray-700 mb-3">Procedure Steps</h4>
                    <div className="space-y-2">{protocol.steps.map((step, index) => (
                      <div key={step} className="flex items-start gap-3 p-3 rounded-xl bg-gray-50"><span className="w-7 h-7 rounded-full bg-gradient-to-br from-gray-200 to-gray-300 flex items-center justify-center text-xs font-bold text-gray-600 flex-shrink-0">{index + 1}</span><p className="text-sm text-gray-700">{step}</p></div>
                    ))}</div>
                  </div>
                  <div className="bg-violet-50 rounded-xl p-4"><h4 className="font-semibold text-sm text-violet-700 mb-3">Autism-Specific Considerations</h4>
                    <div className="space-y-2">{protocol.autismConsiderations.map((tip) => (
                      <div key={tip} className="flex items-start gap-2"><CheckCircle size={14} className="text-violet-500 mt-0.5 flex-shrink-0" /><p className="text-xs text-violet-700">{tip}</p></div>
                    ))}</div>
                  </div>
                  <Button type="button" onClick={() => toggleAck(protocol.id)}
                    leadingIcon={<CheckCircle size={14} />}
                    className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium transition-all ${acknowledged.has(protocol.id) ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : 'bg-violet-100 text-violet-700 hover:bg-violet-200'}`}>
                    {acknowledged.has(protocol.id) ? 'Acknowledged' : 'I Have Read and Understand This Protocol'}
                  </Button>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
