"use client"

import { useState } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
    Plus,
    FileText,
    Clock,
    Globe,
    Tag,
    Loader2,
    ChevronRight,
    MessageSquare,
    Sparkles,
    Edit2,
    CheckCircle2
} from "lucide-react"
import { useGetTemplateDraftList, useUpdateTemplateDraft } from "@/lib/react-query/hooks/whatsapp"
import { TemplateDraftItem, UpdateTemplateDraftPayload } from "@/types/whatsapp"
import { useToaster } from "@/context/ToasterContext"
import { Skeleton } from "@/components/ui/skeleton"

interface TemplateListProps {
    onSelectTemplate: (template: TemplateDraftItem) => void
    onCreateNew: () => void
}

const statusColors: Record<string, string> = {
    DRAFT: "bg-amber-100 text-amber-700 border-amber-200",
    APPROVED: "bg-emerald-100 text-emerald-700 border-emerald-200",
    REJECTED: "bg-red-100 text-red-700 border-red-200",
    PENDING: "bg-blue-100 text-blue-700 border-blue-200",
}

const categoryIcons: Record<string, React.ReactNode> = {
    UTILITY: <Tag className="w-4 h-4" />,
    MARKETING: <Sparkles className="w-4 h-4" />,
    AUTHENTICATION: <Globe className="w-4 h-4" />,
}

function formatDate(dateString: string) {
    return new Date(dateString).toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
    })
}

export function WhatsAppTemplateList({ onSelectTemplate, onCreateNew }: TemplateListProps) {
    const { data, isLoading } = useGetTemplateDraftList()
    const updateTemplate = useUpdateTemplateDraft()
    const templates = data?.templates || []
    const toast = useToaster()

    const handleSetPrimary = (e: React.MouseEvent, template: TemplateDraftItem) => {
        if (template.status !== "APPROVED") {
            toast.showError("Only approved templates can be selected as primary.")
            return
        }

        updateTemplate.mutate({
            id: template._id,
            payload: { isPrimary: !template.isPrimary } as UpdateTemplateDraftPayload
        })
    }

    if (isLoading) {
        return (
            <div className="space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div className="space-y-2 w-full max-w-lg">
                        <Skeleton className="h-4 w-full" />
                        <Skeleton className="h-4 w-3/4" />
                    </div>
                    <Skeleton className="h-10 w-40 shrink-0" />
                </div>

                <div className="space-y-4">
                    <Skeleton className="h-5 w-48" />
                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                        {[1, 2, 3, 4, 5, 6].map((i) => (
                            <Card key={i} className="shadow-card border-none bg-white">
                                <CardContent className="p-5 space-y-4">
                                    <div className="flex items-start justify-between">
                                        <div className="flex items-center gap-3 min-w-0">
                                            <Skeleton className="w-10 h-10 rounded-xl shrink-0" />
                                            <div className="space-y-1.5 min-w-0">
                                                <Skeleton className="h-4 w-24" />
                                                <Skeleton className="h-3 w-20" />
                                            </div>
                                        </div>
                                        <Skeleton className="w-8 h-8 rounded-full shrink-0" />
                                    </div>

                                    <div className="flex flex-wrap gap-2">
                                        <Skeleton className="h-5 w-16 rounded-full" />
                                        <Skeleton className="h-5 w-20 rounded-full" />
                                        <Skeleton className="h-5 w-16 rounded-full" />
                                    </div>

                                    <div className="flex items-center gap-1.5 pt-1 border-t border-gray-50">
                                        <Skeleton className="w-3.5 h-3.5 rounded-full" />
                                        <Skeleton className="h-3 w-24" />
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                </div>
            </div>
        )
    }

    return (
        <div className="space-y-6 animate-fade-in">
            <div className="flex items-center justify-end">
                <Button
                    onClick={onCreateNew}
                    className="gap-2 bg-primary-gradient text-white shrink-0"
                >
                    <Plus className="w-4 h-4" />
                    Create Template
                </Button>
            </div>

            {templates.length === 0 ? (
                <Card className="shadow-card border-none bg-white">
                    <CardContent className="flex flex-col items-center justify-center py-16 space-y-4">
                        <div className="w-20 h-20 rounded-full bg-primary/5 flex items-center justify-center">
                            <MessageSquare className="w-10 h-10 text-primary/40" />
                        </div>
                        <div className="text-center space-y-2">
                            <h3 className="text-lg font-semibold text-gray-900">No templates yet</h3>
                            <p className="text-muted-foreground text-sm max-w-md">
                                Create your first WhatsApp message template to start communicating with your customers
                            </p>
                        </div>
                        <Button
                            onClick={onCreateNew}
                            className="gap-2 bg-primary-gradient text-white mt-2"
                        >
                            <Plus className="w-4 h-4" />
                            Create Your First Template
                        </Button>
                    </CardContent>
                </Card>
            ) : (
                <div className="space-y-4">
                    <div className="space-y-1">
                        <div className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                            <MessageSquare className="w-4 h-4 text-primary" />
                            <h3>Select an approved template to use, or click again to disable</h3>
                        </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                        {templates.map((template) => (
                            <Card
                                key={template._id}
                                className={`shadow-card border-2 transition-all duration-300 relative overflow-hidden ${template.isPrimary
                                    ? "border-primary bg-primary/5"
                                    : template.status === 'APPROVED'
                                        ? "border-transparent bg-white hover:shadow-lg cursor-pointer group"
                                        : "border-transparent bg-gray-50/50 opacity-80"
                                    }`}
                                onClick={(e) => handleSetPrimary(e, template)}
                            >
                                {template.isPrimary && (
                                    <div className="absolute top-0 right-0 p-1 flex items-center gap-1.5 bg-primary text-white rounded-bl-lg px-2 py-0.5">
                                        <span className="text-[10px] font-bold uppercase tracking-wider">Primary Template</span>
                                        <CheckCircle2 className="w-3.5 h-3.5" />
                                    </div>
                                )}
                                <CardContent className="p-5 space-y-4">
                                    {/* Header Row */}
                                    <div className="flex items-start justify-between">
                                        <div className="flex items-center gap-3 min-w-0">
                                            <div className={`w-10 h-10 rounded-xl bg-primary/5 flex items-center justify-center shrink-0 transition-colors ${template.status === 'APPROVED' ? 'group-hover:bg-primary/10' : ''}`}>
                                                <FileText className="w-5 h-5 text-primary" />
                                            </div>
                                            <div className="min-w-0">
                                                <h3 className="font-semibold text-gray-900 truncate text-sm">
                                                    {template.name || template.internalName}
                                                </h3>
                                                <p className="text-xs text-muted-foreground truncate">
                                                    {template.internalName}
                                                </p>
                                            </div>
                                        </div>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="w-8 h-8 rounded-full hover:bg-primary/10 hover:text-primary transition-colors shrink-0"
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                onSelectTemplate(template)
                                            }}
                                        >
                                            <Edit2 className="w-4 h-4 text-gray-400 group-hover:text-primary transition-colors" />
                                        </Button>
                                    </div>

                                    {/* Badges Row */}
                                    <div className="flex flex-wrap gap-2">
                                        <Badge
                                            variant="outline"
                                            className={`text-[11px] font-medium border ${statusColors[template.status] || "bg-gray-100 text-gray-600 border-gray-200"}`}
                                        >
                                            {template.status}
                                        </Badge>
                                        <Badge
                                            variant="outline"
                                            className="text-[11px] font-medium border-gray-200 text-gray-500 gap-1"
                                        >
                                            {categoryIcons[template.category] || <Tag className="w-3 h-3" />}
                                            {template.category}
                                        </Badge>
                                        <Badge
                                            variant="outline"
                                            className="text-[11px] font-medium border-gray-200 text-gray-500 gap-1"
                                        >
                                            <Globe className="w-3 h-3" />
                                            {template.language}
                                        </Badge>
                                    </div>

                                    {/* Footer */}
                                    <div className="flex items-center gap-1.5 text-xs text-muted-foreground pt-1 border-t border-gray-50">
                                        <Clock className="w-3.5 h-3.5" />
                                        <span>{formatDate(template.updatedAt)}</span>
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                </div>
            )
            }
        </div >
    )
}
