import { useState, useEffect } from 'react';
import {
    MessageSquare, Plus, Clock, User, AlertTriangle, Send, X,
    ChevronDown, ChevronUp, Check, Bell
} from 'lucide-react';
import { messagingApi, ShiftNote } from '../../lib/messagingApi';

interface ShiftNotesWidgetProps {
    roomId?: string;
    batchId?: string;
    compact?: boolean;
    maxItems?: number;
    showCreateButton?: boolean;
    className?: string;
}

const IMPORTANCE_CONFIG: Record<string, { color: string; bgColor: string; label: string }> = {
    LOW: { color: 'text-[var(--color-text-tertiary)]', bgColor: 'bg-[var(--color-bg-tertiary)]', label: 'Low' },
    NORMAL: { color: 'text-[var(--color-accent)]', bgColor: 'bg-blue-50 dark:bg-blue-900/30', label: 'Normal' },
    HIGH: { color: 'text-[var(--color-warning)]', bgColor: 'bg-amber-50 dark:bg-amber-900/30', label: 'High' },
    URGENT: { color: 'text-red-500', bgColor: 'bg-red-50 dark:bg-red-900/30', label: 'Urgent' }
};

export default function ShiftNotesWidget({
    roomId,
    batchId,
    compact = false,
    maxItems = 5,
    showCreateButton = true,
    className = ''
}: ShiftNotesWidgetProps) {
    const [notes, setNotes] = useState<ShiftNote[]>([]);
    const [loading, setLoading] = useState(true);
    const [expanded, setExpanded] = useState(!compact);
    const [showCreate, setShowCreate] = useState(false);
    const [newNote, setNewNote] = useState<{ content: string; importance: 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT' }>({ content: '', importance: 'NORMAL' });
    const [submitting, setSubmitting] = useState(false);

    useEffect(() => {
        loadNotes();
    }, [roomId, batchId]);

    async function loadNotes() {
        setLoading(true);
        try {
            const data = await messagingApi.getShiftNotes({ roomId, batchId, limit: maxItems });
            setNotes(data);
        } catch (error) {
            console.error('Failed to load shift notes:', error);
        } finally {
            setLoading(false);
        }
    }

    async function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        if (!newNote.content.trim()) return;

        setSubmitting(true);
        try {
            const created = await messagingApi.createShiftNote({
                content: newNote.content,
                roomId,
                batchId,
                importance: newNote.importance
            });
            setNotes(prev => [created, ...prev].slice(0, maxItems));
            setNewNote({ content: '', importance: 'NORMAL' });
            setShowCreate(false);
        } catch (error) {
            console.error('Failed to create shift note:', error);
        } finally {
            setSubmitting(false);
        }
    }

    async function handleMarkRead(id: string) {
        try {
            await messagingApi.markShiftNoteRead(id);
            setNotes(prev => prev.map(n => n.id === id ? { ...n, isRead: true } : n));
        } catch (error) {
            console.error('Failed to mark as read:', error);
        }
    }

    function formatTime(ts: string) {
        const date = new Date(ts);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMins / 60);

        if (diffMins < 1) return 'Just now';
        if (diffMins < 60) return `${diffMins}m ago`;
        if (diffHours < 24) return `${diffHours}h ago`;
        return date.toLocaleDateString();
    }

    const unreadCount = notes.filter(n => !n.isRead).length;
    const urgentNotes = notes.filter(n => n.importance === 'URGENT' || n.importance === 'HIGH');

    return (
        <div className={`bg-[var(--color-bg-elevated)] rounded-xl border border-[var(--color-border-default)] overflow-hidden ${className}`}>
            {/* Header */}
            <div
                className="p-4 border-b border-[var(--color-border-default)] flex items-center justify-between cursor-pointer"
                onClick={() => compact && setExpanded(!expanded)}
            >
                <div className="flex items-center gap-3">
                    <div className="relative">
                        <MessageSquare className="text-indigo-500" size={20} />
                        {unreadCount > 0 && (
                            <span className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full text-[10px] text-white flex items-center justify-center font-bold">
                                {unreadCount}
                            </span>
                        )}
                    </div>
                    <div>
                        <h3 className="font-medium text-[var(--color-text-primary)]">Shift Notes</h3>
                        {compact && !expanded && (
                            <p className="text-xs text-[var(--color-text-tertiary)]">
                                {notes.length} note{notes.length !== 1 ? 's' : ''}{urgentNotes.length > 0 && ` • ${urgentNotes.length} urgent`}
                            </p>
                        )}
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {showCreateButton && expanded && (
                        <button
                            onClick={(e) => { e.stopPropagation(); setShowCreate(true); }}
                            className="p-1.5 rounded-lg bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-200 dark:hover:bg-indigo-900/50 transition-colors"
                        >
                            <Plus size={16} />
                        </button>
                    )}
                    {compact && (
                        <button className="p-1 text-[var(--color-text-tertiary)]">
                            {expanded ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
                        </button>
                    )}
                </div>
            </div>

            {/* Create Form */}
            {showCreate && expanded && (
                <form onSubmit={handleSubmit} className="p-4 bg-[var(--color-bg-tertiary)]/50 border-b border-[var(--color-border-default)]">
                    <div className="space-y-3">
                        <textarea
                            value={newNote.content}
                            onChange={(e) => setNewNote({ ...newNote, content: e.target.value })}
                            placeholder="Add a note for the next shift..."
                            rows={3}
                            className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-600 bg-[var(--color-bg-elevated)] text-sm resize-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                            autoFocus
                        />
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                                <span className="text-xs text-[var(--color-text-tertiary)]">Importance:</span>
                                {(['LOW', 'NORMAL', 'HIGH', 'URGENT'] as const).map(level => (
                                    <button
                                        key={level}
                                        type="button"
                                        onClick={() => setNewNote({ ...newNote, importance: level })}
                                        className={`px-2 py-0.5 rounded text-xs font-medium transition-colors ${newNote.importance === level
                                            ? `${IMPORTANCE_CONFIG[level].bgColor} ${IMPORTANCE_CONFIG[level].color}`
                                            : 'text-[var(--color-text-tertiary)] hover:text-slate-600'
                                            }`}
                                    >
                                        {IMPORTANCE_CONFIG[level].label}
                                    </button>
                                ))}
                            </div>
                            <div className="flex gap-2">
                                <button
                                    type="button"
                                    onClick={() => setShowCreate(false)}
                                    className="px-3 py-1.5 text-sm text-[var(--color-text-tertiary)] hover:text-slate-700"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={!newNote.content.trim() || submitting}
                                    className="px-3 py-1.5 bg-indigo-600 text-white rounded-lg text-sm font-medium flex items-center gap-1.5 hover:bg-indigo-700 disabled:opacity-50"
                                >
                                    <Send size={14} />
                                    {submitting ? 'Sending...' : 'Post'}
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            )}

            {/* Notes List */}
            {expanded && (
                <div className="divide-y divide-slate-100 dark:divide-slate-700">
                    {loading ? (
                        <div className="p-8 text-center text-[var(--color-text-tertiary)] text-sm">Loading notes...</div>
                    ) : notes.length === 0 ? (
                        <div className="p-8 text-center">
                            <MessageSquare className="mx-auto mb-2 text-slate-300" size={32} />
                            <p className="text-[var(--color-text-tertiary)] text-sm">No shift notes yet</p>
                            <p className="text-[var(--color-text-tertiary)] text-xs mt-1">Add a note to communicate with other shifts</p>
                        </div>
                    ) : (
                        notes.map(note => {
                            const config = IMPORTANCE_CONFIG[note.importance];
                            const isUrgent = note.importance === 'URGENT' || note.importance === 'HIGH';

                            return (
                                <div
                                    key={note.id}
                                    className={`p-4 transition-colors ${!note.isRead ? 'bg-indigo-50/50 dark:bg-indigo-900/10' : ''
                                        } ${isUrgent ? 'border-l-4 border-l-amber-500' : ''}`}
                                >
                                    <div className="flex items-start gap-3">
                                        <div className={`p-1.5 rounded-full ${config.bgColor}`}>
                                            {isUrgent ? (
                                                <AlertTriangle size={14} className={config.color} />
                                            ) : (
                                                <MessageSquare size={14} className={config.color} />
                                            )}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <p className="text-sm text-[var(--color-text-secondary)]late-200 whitespace-pre-wrap">
                                                {note.content}
                                            </p>
                                            <div className="flex items-center gap-3 mt-2 text-xs text-[var(--color-text-tertiary)]">
                                                <span className="flex items-center gap-1">
                                                    <User size={12} />
                                                    {note.createdBy?.name || 'Unknown'}
                                                </span>
                                                <span className="flex items-center gap-1">
                                                    <Clock size={12} />
                                                    {formatTime(note.createdAt)}
                                                </span>
                                                <span className={`px-1.5 py-0.5 rounded ${config.bgColor} ${config.color}`}>
                                                    {config.label}
                                                </span>
                                            </div>
                                        </div>
                                        {!note.isRead && (
                                            <button
                                                onClick={() => handleMarkRead(note.id)}
                                                className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-[var(--color-text-tertiary)] hover:text-[var(--color-primary)] transition-colors"
                                                title="Mark as read"
                                            >
                                                <Check size={16} />
                                            </button>
                                        )}
                                    </div>
                                </div>
                            );
                        })
                    )}
                </div>
            )}

            {/* View All Link */}
            {expanded && notes.length > 0 && (
                <div className="p-3 border-t border-[var(--color-border-default)] text-center">
                    <button className="text-sm text-indigo-600 hover:text-indigo-700 font-medium">
                        View All Notes
                    </button>
                </div>
            )}
        </div>
    );
}
