import { AlertTriangle, CheckCircle, ChevronDown, ChevronUp, Pencil, Plus, Trash2 } from 'lucide-react';

import { useSafetyProtocolsModule } from '@/business/safety-protocols/hooks';
import { safetyStyleForTag } from '@/shared/constants/safetyProtocols';
import { Button } from '@/components/ui/button';
import { StatePanel } from '@/components/ui/state-panel';
import { SafetyProtocolForm } from '@/components/safety-protocols/SafetyProtocolForm';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';

export function SafetyProtocolsModule() {
  const workflow = useSafetyProtocolsModule();
  const errorMessage = getOptionalErrorMessage(workflow.error);
  const { protocols, acknowledgedIds, canManage } = workflow;
  const isFormOpen = workflow.showNewForm || workflow.editId !== null;

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-100 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-slate-400 mt-1">Clear, visual safety standards - always accessible, always current</p>
        </div>
        {canManage && !isFormOpen && (
          <Button
            type="button"
            onClick={workflow.openNewForm}
            leadingIcon={<Plus size={16} />}
            className="flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white rounded-xl font-medium text-sm hover:shadow-lg hover:shadow-violet-500/25 transition-all"
          >
            New Protocol
          </Button>
        )}
      </div>

      {workflow.showNewForm && <SafetyProtocolForm workflow={workflow} />}

      <div className="space-y-4">
        {workflow.isLoading && (
          <StatePanel tone="red" alignment="center" loading>
            Loading safety protocols...
          </StatePanel>
        )}
        {errorMessage && (
          <StatePanel tone="red" role="alert">
            {errorMessage}
          </StatePanel>
        )}
        {!workflow.isLoading && !errorMessage && protocols.length === 0 && (
          <StatePanel>
            No safety protocols are published yet.
          </StatePanel>
        )}
        {!workflow.isLoading && !errorMessage && protocols.map((protocol) => {
          if (workflow.editId === protocol.id) {
            return <SafetyProtocolForm key={protocol.id} workflow={workflow} />;
          }

          const { icon: ProtocolIcon, color } = safetyStyleForTag(protocol.tag);
          const isAcknowledged = acknowledgedIds.has(protocol.id);
          const isExpanded = workflow.expandedId === protocol.id;

          return (
            <div key={protocol.id} className="rounded-2xl border border-slate-700/70 bg-slate-900/75 shadow-sm shadow-black/10 overflow-hidden">
              <Button type="button" onClick={() => workflow.toggleExpanded(protocol.id)} className="w-full h-auto px-5 py-4 flex items-center justify-between bg-transparent text-inherit transition-colors hover:bg-slate-800/60">
                <div className="flex items-center gap-3">
                  <div className={`w-10 h-10 rounded-xl bg-gradient-to-br ${color} flex items-center justify-center text-white`}>
                    <ProtocolIcon size={20} />
                  </div>
                  <div className="text-left"><h3 className="font-semibold text-slate-100">{protocol.title}</h3><p className="text-xs text-slate-400">{protocol.steps.length} steps - {protocol.autismConsiderations.length} autism considerations</p></div>
                </div>
                <div className="flex items-center gap-3">
                  {workflow.canPersistAcknowledgments && isAcknowledged && <span className="px-2.5 py-1 bg-emerald-500/15 text-emerald-200 rounded-lg text-[10px] font-semibold">ACKNOWLEDGED</span>}
                  {isExpanded ? <ChevronUp size={18} className="text-slate-400" /> : <ChevronDown size={18} className="text-slate-400" />}
                </div>
              </Button>
              {isExpanded && (
                <div className="px-5 pb-5 space-y-4 border-t border-slate-700/60 pt-4">
                  {protocol.steps.length > 0 && (
                    <div><h4 className="font-semibold text-sm text-slate-200 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-slate-950/50 border border-slate-700/50"><span className="w-7 h-7 rounded-full bg-slate-800 flex items-center justify-center text-xs font-bold text-slate-300 flex-shrink-0">{index + 1}</span><p className="text-sm text-slate-300">{step}</p></div>
                      ))}</div>
                    </div>
                  )}
                  {protocol.autismConsiderations.length > 0 && (
                    <div className="bg-violet-500/10 border border-violet-400/20 rounded-xl p-4"><h4 className="font-semibold text-sm text-violet-200 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-300 mt-0.5 flex-shrink-0" /><p className="text-xs text-violet-100/90">{tip}</p></div>
                      ))}</div>
                    </div>
                  )}
                  <div className="flex flex-wrap items-center gap-3">
                    {workflow.canPersistAcknowledgments && (
                      <Button type="button" onClick={() => workflow.acknowledge(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 ${isAcknowledged ? 'bg-emerald-500/15 text-emerald-200 hover:bg-emerald-500/20' : 'bg-violet-500/15 text-violet-200 hover:bg-violet-500/20'}`}>
                        {isAcknowledged ? 'Acknowledged' : 'I Have Read and Understand This Protocol'}
                      </Button>
                    )}
                    {canManage && (
                      <>
                        <Button type="button" onClick={() => workflow.startEditing(protocol)}
                          leadingIcon={<Pencil size={14} />}
                          className="flex items-center gap-2 px-4 py-2.5 bg-slate-800 text-slate-300 rounded-xl text-sm font-medium hover:bg-slate-700 transition-colors">
                          Edit
                        </Button>
                        <Button type="button" onClick={() => { void workflow.deleteProtocol(protocol.id); }}
                          disabled={workflow.isDeleting}
                          loading={workflow.isDeleting}
                          loadingLabel="Deleting..."
                          leadingIcon={<Trash2 size={14} />}
                          className="flex items-center gap-2 px-4 py-2.5 bg-red-500/10 text-red-200 rounded-xl text-sm font-medium hover:bg-red-500/20 transition-colors disabled:opacity-50">
                          Delete
                        </Button>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
