import { useState } from 'react';
import { AlertTriangle, CheckCircle, Database, FileText, MessageSquare, Send } from 'lucide-react';

import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import {
  useParentMessages,
  useSendParentMessage,
} from '@/business/communications/hooks';
import { getTemplateCategory } from '@/business/communications/selectors';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { StatePanel } from '@/components/ui/state-panel';
import { Textarea } from '@/components/ui/textarea';
import {
  PARENT_MESSAGE_CATEGORY_COLORS,
  PARENT_MESSAGE_CATEGORY_FILTERS,
  PARENT_MESSAGE_SUCCESS_CLEAR_DELAY_MS,
} from '@/shared/constants/communications';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import type {
  ParentMessageCategory,
  ParentTemplate,
} from '@/shared/types/communications';

export function ParentCommunicationModule() {
  const [selectedTemplate, setSelectedTemplate] = useState<string | null>(null);
  const [messageText, setMessageText] = useState('');
  const [recipientName, setRecipientName] = useState('');
  const [showSuccess, setShowSuccess] = useState(false);
  const [categoryFilter, setCategoryFilter] = useState<ParentMessageCategory | 'all'>('all');
  const messagesQuery = useParentMessages();
  const sendMessageMutation = useSendParentMessage();
  const templatesQuery = useContentCatalogPayload<readonly ParentTemplate[]>(
    CONTENT_CATALOG_TYPES.parentMessageTemplates,
    [],
  );
  const sentMessages = messagesQuery.data ?? [];
  const saving = sendMessageMutation.isPending;
  const messageError = getOptionalErrorMessage(messagesQuery.error);
  const sendError = getOptionalErrorMessage(sendMessageMutation.error);
  const templatesError = getOptionalErrorMessage(templatesQuery.error);
  const errorMessage = messageError ?? sendError;
  const parentTemplates = templatesQuery.payload;
  const filteredTemplates = parentTemplates.filter((template) => categoryFilter === 'all' || template.category === categoryFilter);

  const handleSend = async () => {
    if (!messageText.trim() || !recipientName.trim()) return;
    await sendMessageMutation.mutateAsync({
      recipientName,
      messageText,
      category: getTemplateCategory(selectedTemplate, parentTemplates),
    });
    setMessageText('');
    setRecipientName('');
    setShowSuccess(true);
    setTimeout(() => setShowSuccess(false), PARENT_MESSAGE_SUCCESS_CLEAR_DELAY_MS);
  };

  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-cyan-400 to-cyan-600 flex items-center justify-center"><MessageSquare size={20} className="text-white" /></div>
          Parent Communication
        </h2>
        <p className="text-sm text-gray-500 mt-1">FERPA-compliant messaging with pre-approved templates and communication logs</p>
      </div>
      {showSuccess && (
        <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4 flex items-center gap-3">
          <CheckCircle size={18} className="text-emerald-600" />
          <p className="text-sm text-emerald-700 font-medium">Message sent and saved to database!</p>
        </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>
      )}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-3">Pre-Approved Templates</h3>
          <div className="flex gap-2 mb-3 flex-wrap">
            {PARENT_MESSAGE_CATEGORY_FILTERS.map((category) => (
              <Button key={category} type="button" onClick={() => setCategoryFilter(category)} className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${categoryFilter === category ? 'bg-cyan-700 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                {category.charAt(0).toUpperCase() + category.slice(1)}
              </Button>
            ))}
          </div>
          <div className="space-y-2 max-h-80 overflow-y-auto">
            {templatesQuery.isLoading ? (
              <StatePanel tone="cyan" alignment="center" loading className="border-0 bg-transparent">
                Loading templates...
              </StatePanel>
            ) : templatesError ? (
              <StatePanel tone="red" role="alert">{templatesError}</StatePanel>
            ) : filteredTemplates.length > 0 ? filteredTemplates.map((template) => (
              <Button key={template.id} type="button" onClick={() => { setSelectedTemplate(template.id); setMessageText(template.template); }}
                className={`w-full h-auto text-left justify-start p-3 rounded-xl border transition-all ${selectedTemplate === template.id ? 'border-cyan-300 bg-cyan-50' : 'border-gray-100 bg-gray-50 hover:bg-cyan-50/50'}`}>
                <div>
                  <div className="flex items-center gap-2 mb-1"><span className={`px-2 py-0.5 rounded text-[10px] font-semibold ${PARENT_MESSAGE_CATEGORY_COLORS[template.category]}`}>{template.category}</span></div>
                  <p className="text-xs text-gray-600 line-clamp-2">{template.template}</p>
                </div>
              </Button>
            )) : (
              <div className="bg-gray-50 border border-gray-100 rounded-xl p-4 text-sm text-gray-600">
                No templates are available for this category.
              </div>
            )}
          </div>
        </div>
        <div className="space-y-4">
          <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
            <h3 className="font-semibold text-gray-800 mb-3">Compose Message</h3>
            <div className="space-y-3">
              <Input type="text" value={recipientName} onChange={(event) => setRecipientName(event.target.value)} placeholder="Parent/Guardian name..." className="w-full px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-cyan-300 outline-none" />
              <Textarea value={messageText} onChange={(event) => setMessageText(event.target.value)} placeholder="Type or select a template..." rows={5} className="w-full px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-cyan-300 outline-none resize-none" />
              <Button type="button" onClick={() => { void handleSend(); }} disabled={!messageText.trim() || !recipientName.trim() || saving} loading={saving} loadingLabel="Sending..." leadingIcon={<Send size={14} />}
                className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-gradient-to-r from-cyan-500 to-blue-500 text-white rounded-xl font-medium text-sm hover:shadow-lg transition-all disabled:opacity-50">
                Send Message
              </Button>
            </div>
          </div>
          {messagesQuery.isLoading ? (
            <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
              <StatePanel tone="cyan" alignment="center" loading className="border-0 bg-transparent">
                Loading message log...
              </StatePanel>
            </div>
          ) : sentMessages.length > 0 && (
            <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
              <h3 className="font-semibold text-gray-800 mb-3 flex items-center gap-2"><FileText size={16} className="text-gray-400" /> Communication Log <span className="text-[10px] text-emerald-600 flex items-center gap-1"><Database size={10} /> Persisted</span></h3>
              <div className="space-y-2 max-h-48 overflow-y-auto">
                {sentMessages.map((message) => (
                  <div key={message.id} className="p-3 rounded-xl bg-gray-50 border border-gray-100">
                    <div className="flex justify-between items-center mb-1"><span className="text-xs font-medium text-gray-700">To: {message.to}</span><span className="text-[10px] text-gray-400">{message.date}</span></div>
                    <p className="text-xs text-gray-500 line-clamp-2">{message.text}</p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
