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';
import type { UserRole } from '@/shared/types/app';

interface SafetyProtocolsModuleProps {
  readonly userRole: UserRole;
}

export function SafetyProtocolsModule({ userRole }: SafetyProtocolsModuleProps) {
  const workflow = useSafetyProtocolsModule(userRole);
  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-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>
        {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="bg-white rounded-2xl border border-violet-100 shadow-sm overflow-hidden">
              <Button type="button" onClick={() => workflow.toggleExpanded(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 ${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-600">{protocol.steps.length} steps - {protocol.autismConsiderations.length} autism considerations</p></div>
                </div>
                <div className="flex items-center gap-3">
                  {isAcknowledged && <span className="px-2.5 py-1 bg-emerald-100 text-emerald-700 rounded-lg text-[10px] font-semibold">ACKNOWLEDGED</span>}
                  {isExpanded ? <ChevronUp size={18} className="text-gray-400" /> : <ChevronDown size={18} className="text-gray-400" />}
                </div>
              </Button>
              {isExpanded && (
                <div className="px-5 pb-5 space-y-4">
                  {protocol.steps.length > 0 && (
                    <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>
                  )}
                  {protocol.autismConsiderations.length > 0 && (
                    <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>
                  )}
                  <div className="flex flex-wrap items-center gap-3">
                    <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-100 text-emerald-700 hover:bg-emerald-200' : 'bg-violet-100 text-violet-700 hover:bg-violet-200'}`}>
                      {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-gray-100 text-gray-600 rounded-xl text-sm font-medium hover:bg-gray-200 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-50 text-red-500 rounded-xl text-sm font-medium hover:bg-red-100 transition-colors disabled:opacity-50">
                          Delete
                        </Button>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
