"use client";

import { useState, useEffect } from "react";
import {
    MessageSquare,
    Lock,
    Globe,
    Trash2,
    Loader2,
    Send,
    AlertCircle
} from "lucide-react";
import { getCandidateNotes, createCandidateNote, deleteCandidateNote } from "@/app/actions/noteActions";

interface NotesPanelProps {
    applicationId: string;
    currentUserId: string;
}

export function NotesPanel({ applicationId, currentUserId }: NotesPanelProps) {
    const [notes, setNotes] = useState<any[]>([]);
    const [content, setContent] = useState("");
    const [isPrivate, setIsPrivate] = useState(false);

    const [isLoading, setIsLoading] = useState(true);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [deletingId, setDeletingId] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        let isMounted = true;
        async function fetchNotes() {
            try {
                const res = await getCandidateNotes(applicationId);
                if (res.success && isMounted) {
                    setNotes(res.notes ?? []);
                }
            } catch (err) {
                console.error("Failed to fetch notes:", err);
            } finally {
                if (isMounted) setIsLoading(false);
            }
        }
        fetchNotes();
        return () => { isMounted = false; };
    }, [applicationId]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!content.trim()) return;

        setIsSubmitting(true);
        setError(null);

        try {
            const res = await createCandidateNote(applicationId, content, isPrivate);
            if (res.success && res.note) {
                setNotes([res.note, ...notes]);
                setContent("");
                setIsPrivate(false);
            } else {
                setError(res.error || "Failed to add note");
            }
        } catch (err) {
            setError("Something went wrong");
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleDelete = async (noteId: string) => {
        if (!confirm("Are you sure you want to delete this note?")) return;

        setDeletingId(noteId);
        try {
            const res = await deleteCandidateNote(noteId);
            if (res.success) {
                setNotes(notes.filter(n => n.id !== noteId));
            } else {
                setError(res.error || "Failed to delete note");
                setTimeout(() => setError(null), 3000);
            }
        } catch (err) {
            setError("Failed to delete");
        } finally {
            setDeletingId(null);
        }
    };

    return (
        <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden flex flex-col h-[500px]">
            {/* Header */}
            <div className="px-5 py-4 border-b border-slate-100 bg-slate-50 flex items-center justify-between shrink-0">
                <div className="flex items-center gap-2">
                    <MessageSquare className="w-4 h-4 text-primary" />
                    <h3 className="font-bold text-slate-800">Team Notes</h3>
                </div>
                <span className="text-xs font-semibold bg-white text-slate-500 px-2 py-1 rounded shadow-sm">
                    {notes.length}
                </span>
            </div>

            {/* Error Banner */}
            {error && (
                <div className="mx-4 mt-3 p-2 bg-red-50 border border-red-100 rounded flex items-center gap-2 text-red-600 text-xs shrink-0">
                    <AlertCircle className="w-4 h-4" />
                    {error}
                </div>
            )}

            {/* Notes List */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {isLoading ? (
                    <div className="flex justify-center items-center h-full">
                        <Loader2 className="w-6 h-6 text-slate-300 animate-spin" />
                    </div>
                ) : notes.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-full text-center text-slate-400 space-y-2">
                        <MessageSquare className="w-8 h-8 opacity-20" />
                        <p className="text-sm">No notes yet</p>
                        <p className="text-xs">Add private insights or share with your team</p>
                    </div>
                ) : (
                    notes.map((note) => (
                        <div key={note.id} className="group flex gap-3 text-sm">
                            <div className="flex-shrink-0 mt-0.5">
                                {note.author?.avatar_url ? (
                                    <img src={note.author.avatar_url} alt={note.author.name} className="w-8 h-8 rounded-full object-cover" />
                                ) : (
                                    <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center font-bold text-slate-500 text-xs">
                                        {(note.author?.name || 'U').charAt(0)}
                                    </div>
                                )}
                            </div>

                            <div className="flex-1 min-w-0 bg-slate-50 rounded-xl rounded-tl-none p-3 border border-slate-100 relative">
                                <div className="flex items-center justify-between mb-1">
                                    <span className="font-bold text-slate-800 text-xs">
                                        {note.author?.name || 'Unknown User'}
                                    </span>
                                    <div className="flex items-center gap-2">
                                        {note.is_private ? (
                                            <Lock className="w-3 h-3 text-amber-500" aria-label="Private note" />
                                        ) : (
                                            <Globe className="w-3 h-3 text-slate-400" aria-label="Visible to team" />
                                        )}
                                        <span className="text-[10px] text-slate-400">
                                            {new Date(note.created_at).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}
                                        </span>
                                    </div>
                                </div>

                                <p className="text-slate-600 whitespace-pre-wrap text-[13px] leading-relaxed">
                                    {note.content}
                                </p>

                                {/* Delete button (only for author) */}
                                {note.author_id === currentUserId && (
                                    <button
                                        onClick={() => handleDelete(note.id)}
                                        disabled={deletingId === note.id}
                                        className="absolute -right-2 -top-2 bg-white border border-slate-200 p-1.5 rounded-full text-red-500 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-50 shadow-sm"
                                        title="Delete note"
                                    >
                                        {deletingId === note.id ? (
                                            <Loader2 className="w-3 h-3 animate-spin" />
                                        ) : (
                                            <Trash2 className="w-3 h-3" />
                                        )}
                                    </button>
                                )}
                            </div>
                        </div>
                    ))
                )}
            </div>

            {/* Composer Input */}
            <div className="p-4 border-t border-slate-100 bg-white shrink-0">
                <form onSubmit={handleSubmit} className="flex flex-col gap-2 relative">
                    <textarea
                        value={content}
                        onChange={(e) => setContent(e.target.value)}
                        placeholder="Add a note about this candidate..."
                        className="w-full resize-none text-sm p-3 pr-10 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all bg-slate-50 hover:bg-white"
                        rows={3}
                        disabled={isSubmitting}
                    />

                    <div className="flex items-center justify-between mt-1 px-1">
                        <label className="flex items-center gap-1.5 cursor-pointer text-xs text-slate-500 select-none hover:text-slate-800 transition-colors">
                            <input
                                type="checkbox"
                                checked={isPrivate}
                                onChange={(e) => setIsPrivate(e.target.checked)}
                                disabled={isSubmitting}
                                className="rounded text-primary focus:ring-primary h-3.5 w-3.5 border-slate-300"
                            />
                            {isPrivate ? (
                                <><Lock className="w-3 h-3 text-amber-500" /> Private Note</>
                            ) : (
                                <><Globe className="w-3 h-3" /> Team Shared</>
                            )}
                        </label>

                        <button
                            type="submit"
                            disabled={!content.trim() || isSubmitting}
                            className={`p-2 rounded-lg font-bold text-white transition-colors flex items-center justify-center
                                ${!content.trim() || isSubmitting
                                    ? 'bg-slate-200 text-slate-400 cursor-not-allowed'
                                    : 'bg-primary hover:bg-primary/90 shadow-sm shadow-primary/20'
                                }`}
                        >
                            {isSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4 ml-0.5" />}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}
