import { useState } from 'react';
import { AlertTriangle, Bell, Calendar, Check, CheckCircle, Clock, Users } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import {
  useCommunicationEvents,
  useCreateCommunicationEvent,
} from '@/business/communications/hooks';
import {
  canCreateCommunicationEvents,
  filterCommunicationEventsByRole,
  toCommunicationEventType,
} from '@/business/communications/selectors';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { NativeSelect } from '@/components/ui/native-select';
import { StatePanel } from '@/components/ui/state-panel';
import {
  COMMUNICATION_EVENT_DEFAULT_ROLES,
  COMMUNICATION_EVENT_ICON_BACKGROUNDS,
  COMMUNICATION_EVENT_TYPE_COLORS,
  COMMUNICATION_EVENT_TYPES,
} from '@/shared/constants/communications';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import type { CommunicationEventType } from '@/shared/types/communications';
import type { UserRole } from '@/shared/types/app';

const typeIcons: Record<CommunicationEventType, LucideIcon> = {
  meeting: Users,
  drill: AlertTriangle,
  event: Calendar,
  deadline: Clock,
};

interface InternalAlertsModuleProps {
  readonly userRole: UserRole;
}

export function InternalAlertsModule({ userRole }: InternalAlertsModuleProps) {
  const [acknowledged, setAcknowledged] = useState<Set<string>>(new Set());
  const canCreateEvents = canCreateCommunicationEvents(userRole);
  const [newEventTitle, setNewEventTitle] = useState('');
  const [newEventDate, setNewEventDate] = useState('');
  const [newEventType, setNewEventType] = useState<CommunicationEventType>('meeting');
  const eventsQuery = useCommunicationEvents();
  const createEventMutation = useCreateCommunicationEvent();
  const filteredEvents = filterCommunicationEventsByRole(eventsQuery.data ?? [], userRole);
  const errorMessage = getOptionalErrorMessage(eventsQuery.error) ?? getOptionalErrorMessage(createEventMutation.error);

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

  const addEvent = async () => {
    if (!newEventTitle || !newEventDate) return;
    await createEventMutation.mutateAsync({
      title: newEventTitle,
      date: newEventDate,
      type: newEventType,
      roles: COMMUNICATION_EVENT_DEFAULT_ROLES,
    });
    setNewEventTitle('');
    setNewEventDate('');
  };

  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-rose-400 to-rose-600 flex items-center justify-center"><Bell size={20} className="text-white" /></div>
          Internal Communication & Alerts
        </h2>
        <p className="text-sm text-gray-500 mt-1">Smart notifications, event reminders, and acknowledgment tracking</p>
      </div>
      {canCreateEvents && (
        <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-3">Schedule New Alert</h3>
          <div className="flex flex-col md:flex-row gap-3">
            <Input type="text" value={newEventTitle} onChange={(event) => setNewEventTitle(event.target.value)} placeholder="Event title..." className="flex-1 px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-rose-300 outline-none" />
            <Input type="date" value={newEventDate} onChange={(event) => setNewEventDate(event.target.value)} className="px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-rose-300 outline-none" />
            <NativeSelect value={newEventType} onChange={(event) => setNewEventType(toCommunicationEventType(event.target.value))} className="px-4 py-2.5 border border-gray-200 rounded-xl text-sm bg-white focus:ring-2 focus:ring-rose-300 outline-none">
              {COMMUNICATION_EVENT_TYPES.map((type) => (
                <option key={type} value={type}>{type.charAt(0).toUpperCase() + type.slice(1)}</option>
              ))}
            </NativeSelect>
            <Button type="button" onClick={() => { void addEvent(); }} disabled={createEventMutation.isPending} loading={createEventMutation.isPending} loadingLabel="Adding..." className="px-5 py-2.5 bg-gradient-to-r from-rose-500 to-pink-500 text-white rounded-xl font-medium text-sm hover:shadow-lg transition-all disabled:opacity-50">
              Add Alert
            </Button>
          </div>
        </div>
      )}
      {errorMessage && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-3">
          <AlertTriangle size={18} className="text-red-600" />
          <p className="text-sm text-red-700 font-medium">{errorMessage}</p>
        </div>
      )}
      {eventsQuery.isLoading ? (
        <StatePanel tone="red" alignment="center" loading>
          Loading alerts...
        </StatePanel>
      ) : (
        <div className="space-y-3">
          {filteredEvents.map((event) => {
            const TypeIcon = typeIcons[event.type];

            return (
              <div key={event.id} className={`bg-white rounded-2xl border shadow-sm p-4 flex items-center justify-between ${COMMUNICATION_EVENT_TYPE_COLORS[event.type]}`}>
                <div className="flex items-center gap-3">
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${COMMUNICATION_EVENT_ICON_BACKGROUNDS[event.type]}`}>
                    <TypeIcon size={14} />
                  </div>
                  <div>
                    <h4 className="font-semibold text-sm text-gray-800">{event.title}</h4>
                    <p className="text-xs text-gray-500">{new Date(event.date).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })}</p>
                  </div>
                </div>
                <Button type="button" onClick={() => toggleAck(event.id)} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${acknowledged.has(event.id) ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-100 text-gray-500 hover:bg-emerald-50'}`}>
                  {acknowledged.has(event.id) ? <Check size={12} /> : <CheckCircle size={12} />}
                  {acknowledged.has(event.id) ? 'Acknowledged' : 'Acknowledge'}
                </Button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
