"use client";

import { useState, useEffect } from "react";
import { X, Search, Plus } from "lucide-react";
import { getMessageTemplates, MessageTemplateData, MessageTemplateCategory } from "@/app/actions/messageActions";

interface TemplatePickerProps {
    onSelect: (content: string) => void;
    onClose: () => void;
    contextParams?: Record<string, string>;
}

const CATEGORIES: { value: string; label: string }[] = [
    { value: "all", label: "All Templates" },
    { value: "interview_invite", label: "Interview" },
    { value: "status_update", label: "Updates" },
    { value: "rejection", label: "Rejection" },
    { value: "offer", label: "Offers" },
    { value: "thank_you", label: "Thank You" },
    { value: "follow_up", label: "Follow Up" },
    { value: "custom", label: "Custom" },
];

const DEFAULT_TEMPLATES: MessageTemplateData[] = [
    {
        id: "default-1",
        title: "Interview Invitation",
        category: "interview_invite",
        is_default: true,
        content: "Hi {candidate_name},\n\nThank you for applying for the {job_title} position at {company_name}. We were impressed by your background and would like to invite you for an initial interview.\n\nPlease let us know what times work best for you next week.\n\nBest regards,\n{recruiter_name}"
    },
    {
        id: "default-2",
        title: "Polite Rejection",
        category: "rejection",
        is_default: true,
        content: "Dear {candidate_name},\n\nThank you for taking the time to apply for the {job_title} role at {company_name}.\n\nWhile your skills are impressive, we have decided to move forward with other candidates who more closely fit our current needs.\n\nWe wish you the best in your job search.\n\nSincerely,\nThe {company_name} Team"
    },
    {
        id: "default-3",
        title: "Next Steps / Status Update",
        category: "status_update",
        is_default: true,
        content: "Hi {candidate_name},\n\nI wanted to provide a quick update on your application for the {job_title} position. Our team is currently reviewing your profile and we expect to get back to you by {date_placeholder}.\n\nThanks for your patience!\n\nBest,\n{recruiter_name}"
    },
    {
        id: "default-4",
        title: "Offer Letter",
        category: "offer",
        is_default: true,
        content: "Hi {candidate_name},\n\nWe are thrilled to extend an offer for the {job_title} position at {company_name}!\n\nPlease review the attached offer details and let us know if you have any questions. We look forward to having you on the team.\n\nBest regards,\n{recruiter_name}"
    },
    {
        id: "default-5",
        title: "Follow Up",
        category: "follow_up",
        is_default: true,
        content: "Hi {candidate_name},\n\nI hope you're doing well! I'm following up on your application for the {job_title} position. Could you please confirm your availability for the next step in our process?\n\nLooking forward to hearing from you.\n\nBest,\n{recruiter_name}"
    }
];

export function TemplatePicker({ onSelect, onClose, contextParams = {} }: TemplatePickerProps) {
    const [templates, setTemplates] = useState<MessageTemplateData[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState("");
    const [selectedCategory, setSelectedCategory] = useState<string>("all");

    useEffect(() => {
        async function fetchTemplates() {
            try {
                const result = await getMessageTemplates();
                if (result.success && result.templates && result.templates.length > 0) {
                    setTemplates(result.templates);
                } else {
                    // Fallback to defaults when DB has no templates or action fails (e.g. non-employer)
                    setTemplates(DEFAULT_TEMPLATES);
                }
            } catch (error) {
                console.error("Failed to fetch templates:", error);
                // Gracefully fall back to hardcoded defaults
                setTemplates(DEFAULT_TEMPLATES);
            } finally {
                setIsLoading(false);
            }
        }

        fetchTemplates();

        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === "Escape") onClose();
        };
        window.addEventListener("keydown", handleKeyDown);
        return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);

    const handleSelectTemplate = (template: MessageTemplateData) => {
        let filledContent = template.content;

        // Replace known placeholders with contextParams
        Object.entries(contextParams).forEach(([key, value]) => {
            const regex = new RegExp(`\\{${key}\\}`, "gi");
            filledContent = filledContent.replace(regex, value);
        });

        onSelect(filledContent);
    };

    const filteredTemplates = templates.filter(t => {
        const matchesSearch = t.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
            t.content.toLowerCase().includes(searchQuery.toLowerCase());
        const matchesCategory = selectedCategory === "all" || t.category === selectedCategory;
        return matchesSearch && matchesCategory;
    });

    return (
        <div className="absolute bottom-full mb-3 left-0 w-[420px] max-w-[calc(100vw-40px)] bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden z-50 flex flex-col max-h-[500px]">
            {/* Header */}
            <div className="px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
                <h3 className="font-semibold text-slate-800 tracking-tight">Message Templates</h3>
                <button
                    onClick={onClose}
                    className="p-1 rounded-lg text-slate-400 hover:bg-slate-200 hover:text-slate-700 transition-colors"
                >
                    <X className="w-4 h-4" />
                </button>
            </div>

            {/* Search & Filter */}
            <div className="p-3 border-b border-slate-100 space-y-3">
                <div className="relative">
                    <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                    <input
                        type="text"
                        placeholder="Search templates..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pl-9 pr-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                        autoFocus
                    />
                </div>

                <div className="flex gap-1.5 overflow-x-auto pb-1 scrollbar-hide">
                    {CATEGORIES.map(category => (
                        <button
                            key={category.value}
                            onClick={() => setSelectedCategory(category.value)}
                            className={`px-3 py-1.5 rounded-full text-[11px] font-medium whitespace-nowrap transition-colors ${selectedCategory === category.value
                                    ? "bg-slate-800 text-white"
                                    : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                                }`}
                        >
                            {category.label}
                        </button>
                    ))}
                </div>
            </div>

            {/* Template List */}
            <div className="flex-1 overflow-y-auto p-2 bg-slate-50/30">
                {isLoading ? (
                    <div className="flex justify-center items-center py-10">
                        <div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
                    </div>
                ) : filteredTemplates.length === 0 ? (
                    <div className="text-center py-8">
                        <p className="text-slate-500 text-sm">No templates found.</p>
                        <button className="mt-3 text-xs font-semibold text-primary hover:underline flex items-center justify-center gap-1 mx-auto">
                            <Plus className="w-3.5 h-3.5" />
                            Create New Template
                        </button>
                    </div>
                ) : (
                    <div className="space-y-1.5">
                        {filteredTemplates.map(template => (
                            <button
                                key={template.id}
                                onClick={() => handleSelectTemplate(template)}
                                className="w-full text-left p-3 rounded-xl hover:bg-primary/5 hover:border-primary/20 border border-transparent transition-all group"
                            >
                                <div className="flex items-center justify-between mb-1">
                                    <span className="font-semibold text-sm text-slate-800 group-hover:text-primary transition-colors">
                                        {template.title}
                                    </span>
                                    <span className="text-[10px] uppercase font-bold tracking-wider text-slate-400 bg-slate-100 px-2 py-0.5 rounded-md">
                                        {template.category.replace("_", " ")}
                                    </span>
                                </div>
                                <p className="text-xs text-slate-500 line-clamp-2 leading-relaxed">
                                    {template.content}
                                </p>
                            </button>
                        ))}
                    </div>
                )}
            </div>

            {/* Footer */}
            <div className="p-3 bg-slate-50 border-t border-slate-100 text-center">
                <span className="text-xs text-slate-500">
                    Manage templates in <a href="#" className="text-primary hover:underline font-medium">Settings &gt; Templates</a>
                </span>
            </div>
        </div>
    );
}
