import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useGetTemplates, useDeleteTemplate, Template } from "@/hooks/useTemplateHooks";
import { format } from "date-fns";
import { Loader2, Plus, Search, Trash2, Eye, Edit2, ArrowLeft, Image as ImageIcon, Video, FileText, MoreHorizontal } from "lucide-react";
import { formatPreview } from "@/lib/utils";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

interface TemplateListProps {
    onAdd: () => void;
    onEdit: (id: string) => void;
}

export default function TemplateList({ onAdd, onEdit }: TemplateListProps) {
    const [page, setPage] = useState(1);
    const [searchInput, setSearchInput] = useState("");
    const { data, isLoading } = useGetTemplates(page, searchInput);
    const deleteMutation = useDeleteTemplate();
    
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const [previewModalOpen, setPreviewModalOpen] = useState(false);
    const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);

    const templates: Template[] = data?.result || [];
    const meta = data?.meta;

    const handleDeleteClick = (template: Template) => {
        setSelectedTemplate(template);
        setDeleteModalOpen(true);
    };

    const confirmDelete = async () => {
        if (selectedTemplate) {
            await deleteMutation.mutateAsync(selectedTemplate.id);
            setDeleteModalOpen(false);
            setSelectedTemplate(null);
        }
    };

    const handlePreviewClick = (template: Template) => {
        setSelectedTemplate(template);
        setPreviewModalOpen(true);
    };

    // Extract preview data
    let previewHeaderType = 'NONE';
    let previewHeaderText = '';
    let previewHeaderMedia = null;
    let previewBodyText = '';
    let previewFooterText = '';
    let previewButtons: any[] = [];
    let sampleHeader: string[] = [];
    let sampleBody: string[] = [];

    if (selectedTemplate?.components) {
        const headerComp = selectedTemplate.components.find((c: any) => c.type === 'HEADER');
        if (headerComp) {
            previewHeaderType = headerComp.format;
            if (previewHeaderType === 'TEXT') {
                previewHeaderText = headerComp.text;
                if (headerComp.example?.header_text) sampleHeader = headerComp.example.header_text;
            } else if (['IMAGE', 'VIDEO', 'DOCUMENT'].includes(previewHeaderType)) {
                if (headerComp.example?.header_handle && headerComp.example.header_handle.length > 0) {
                    previewHeaderMedia = (selectedTemplate as any)?.media?.media_url ?? headerComp.example.header_handle[0];
                }
            }
        }

        const bodyComp = selectedTemplate.components.find((c: any) => c.type === 'BODY');
        if (bodyComp) {
            previewBodyText = bodyComp.text || '';
            if (bodyComp.example?.body_text && bodyComp.example.body_text.length > 0) {
                sampleBody = bodyComp.example.body_text[0];
            }
        }

        const footerComp = selectedTemplate.components.find((c: any) => c.type === 'FOOTER');
        if (footerComp) {
            previewFooterText = footerComp.text || '';
        }

        const buttonsComp = selectedTemplate.components.find((c: any) => c.type === 'BUTTONS');
        if (buttonsComp) {
            previewButtons = buttonsComp.buttons || [];
        }
    }

    return (
        <div className="flex flex-col h-full bg-white dark:bg-[#111b21] p-6 overflow-hidden">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-semibold text-gray-800 dark:text-gray-100">Template Whatsapp</h1>
                <Button onClick={onAdd} className="bg-[#00a884] hover:bg-[#008f6f] text-white">
                    <Plus className="w-4 h-4 mr-2" />
                    Tambah Template
                </Button>
            </div>

            <div className="flex items-center mb-4 space-x-2">
                <div className="relative flex-1 max-w-sm">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input 
                        placeholder="Cari template..." 
                        value={searchInput}
                        onChange={(e) => {
                            setSearchInput(e.target.value);
                            setPage(1);
                        }}
                        className="pl-9 bg-gray-50 dark:bg-[#202c33] border-gray-200 dark:border-gray-700"
                    />
                </div>
            </div>

            <div className="flex-1 overflow-auto border border-gray-200 dark:border-gray-800 rounded-md">
                <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                    <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-[#202c33] dark:text-gray-300">
                        <tr>
                            <th className="px-6 py-3">Name</th>
                            <th className="px-6 py-3">Kategori</th>
                            <th className="px-6 py-3">Deskripsi</th>
                            <th className="px-6 py-3 text-center">Pesan Terkirim</th>
                            <th className="px-6 py-3 text-center">Pesan Gagal</th>
                            <th className="px-6 py-3">Status</th>
                            <th className="px-6 py-3 min-w-[200px]">Waktu</th>
                            <th className="px-6 py-3 text-right">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        {isLoading ? (
                            <tr>
                                <td colSpan={8} className="px-6 py-10 text-center">
                                    <Loader2 className="w-6 h-6 animate-spin mx-auto text-gray-400" />
                                </td>
                            </tr>
                        ) : templates.length === 0 ? (
                            <tr>
                                <td colSpan={8} className="px-6 py-10 text-center text-gray-500">
                                    Tidak ada data template.
                                </td>
                            </tr>
                        ) : (
                            templates.map((template) => {
                                const createdBy = template.created_by ? JSON.parse(template.created_by).name : 'System';
                                const updatedBy = template.updated_by ? JSON.parse(template.updated_by).name : 'System';
                                
                                let componentsArray = template.components;
                                if (typeof componentsArray === 'string') {
                                    try {
                                        componentsArray = JSON.parse(componentsArray);
                                    } catch (e) {
                                        componentsArray = [];
                                    }
                                }
                                const bodyComp = Array.isArray(componentsArray) ? componentsArray.find((c: any) => c.type === 'BODY') : null;
                                const description = bodyComp?.text || '-';
                                const truncatedDescription = description.length > 50 ? description.substring(0, 50) + '...' : description;

                                return (
                                    <tr key={template.id} className="bg-white border-b dark:bg-[#111b21] dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-[#202c33]">
                                        <td className="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
                                            {template.name}
                                        </td>
                                        <td className="px-6 py-4">
                                            {template.template_category_name || 'Umum'}
                                        </td>
                                        <td className="px-6 py-4">
                                            {description.length > 50 ? (
                                                <TooltipProvider>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <span className="cursor-help">{truncatedDescription}</span>
                                                        </TooltipTrigger>
                                                        <TooltipContent className="max-w-xs break-words whitespace-pre-wrap">
                                                            <p>{description}</p>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>
                                            ) : (
                                                description
                                            )}
                                        </td>
                                        <td className="px-6 py-4 text-center font-normal text-gray-900 dark:text-gray-100">
                                            {template.messages_sent || 0}
                                        </td>
                                        <td className="px-6 py-4 text-center font-normal text-gray-900 dark:text-gray-100">
                                            {template.messages_failed || 0}
                                        </td>
                                        <td className="px-6 py-4">
                                            <span className={`px-2 py-1 rounded-full text-xs font-medium 
                                                ${template.status === 'APPROVED' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 
                                                  template.status === 'REJECTED' ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200' : 
                                                  'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'}`}>
                                                {template.status_name || template.status}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4">
                                            <div className="flex flex-col space-y-2">
                                                <div className={`flex flex-col ${template.is_created_today ? 'text-green-600 dark:text-green-400' : 'text-gray-500 dark:text-gray-400'}`}>
                                                    <span className="font-semibold text-xs">Dibuat: {createdBy}</span>
                                                    <span className="text-xs">{template.created_at ? format(new Date(template.created_at), 'MMM, dd yyyy HH:mm') : ''}</span>
                                                </div>
                                                {template.updated_at && template.updated_at !== template.created_at && (
                                                    <div className={`flex flex-col ${template.is_update_today ? 'text-green-600 dark:text-green-400' : 'text-gray-500 dark:text-gray-400'}`}>
                                                        <span className="font-semibold text-xs">Diupdate: {updatedBy}</span>
                                                        <span className="text-xs">{template.updated_at ? format(new Date(template.updated_at), 'MMM, dd yyyy HH:mm') : ''}</span>
                                                    </div>
                                                )}
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-500">
                                                        {deleteMutation.isPending && selectedTemplate?.id === template.id ? (
                                                            <Loader2 className="w-4 h-4 animate-spin" />
                                                        ) : (
                                                            <MoreHorizontal className="w-4 h-4" />
                                                        )}
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem onClick={() => handlePreviewClick(template)} className="cursor-pointer">
                                                        <Eye className="w-4 h-4 mr-2" />
                                                        Preview
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem onClick={() => onEdit(template.id)} className="cursor-pointer">
                                                        <Edit2 className="w-4 h-4 mr-2" />
                                                        Edit
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem onClick={() => handleDeleteClick(template)} className="cursor-pointer text-red-600 dark:text-red-400">
                                                        <Trash2 className="w-4 h-4 mr-2" />
                                                        Hapus
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </td>
                                    </tr>
                                );
                            })
                        )}
                    </tbody>
                </table>
            </div>

            {/* Pagination Controls */}
            {meta && meta.last_page > 1 && (
                <div className="flex items-center justify-center space-x-2 mt-4">
                    <Button 
                        variant="outline" 
                        size="sm" 
                        disabled={page === 1}
                        onClick={() => setPage(p => Math.max(1, p - 1))}
                    >
                        Prev
                    </Button>
                    <span className="text-sm text-gray-500 dark:text-gray-400">
                        Page {page} of {meta.last_page}
                    </span>
                    <Button 
                        variant="outline" 
                        size="sm" 
                        disabled={page === meta.last_page}
                        onClick={() => setPage(p => Math.min(meta.last_page, p + 1))}
                    >
                        Next
                    </Button>
                </div>
            )}

            <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Konfirmasi Hapus</DialogTitle>
                        <DialogDescription>
                            Apakah kamu yakin ingin menghapus template <strong>{selectedTemplate?.name}</strong>? Tindakan ini tidak dapat dibatalkan.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setDeleteModalOpen(false)}>Batal</Button>
                        <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
                            {deleteMutation.isPending ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Trash2 className="w-4 h-4 mr-2" />}
                            Hapus
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={previewModalOpen} onOpenChange={setPreviewModalOpen}>
                <DialogContent className="max-w-[400px]">
                    <DialogHeader>
                        <DialogTitle>Preview Template</DialogTitle>
                    </DialogHeader>
                    <div className="flex justify-center bg-[#f0f2f5] dark:bg-[#111b21] p-4 rounded-md">
                        {/* Mock Phone */}
                        <div className="w-[300px] h-[550px] bg-[#efeae2] dark:bg-[#0b141a] rounded-3xl border-[6px] border-gray-800 dark:border-black overflow-hidden relative shadow-xl flex flex-col" style={{ backgroundImage: "url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png')", backgroundSize: 'cover' }}>
                            {/* App Bar */}
                            <div className="bg-[#075e54] dark:bg-[#202c33] h-12 flex items-center px-3 shadow-sm z-10">
                                <ArrowLeft className="w-4 h-4 text-white mr-2" />
                                <div className="w-7 h-7 rounded-full bg-gray-300 dark:bg-gray-600 mr-2"></div>
                                <span className="text-white font-medium text-sm">WhatsApp</span>
                            </div>

                            {/* Chat Area */}
                            <div className="flex-1 p-3 overflow-y-auto flex flex-col">
                                <div className="mt-auto w-full flex flex-col">
                                    <div className="bg-white dark:bg-[#202c33] p-2 rounded-lg rounded-tl-none shadow-sm max-w-[95%] w-full self-start mb-2 relative">
                                    {/* Header Preview */}
                                    {previewHeaderType === 'TEXT' && previewHeaderText && (
                                        <p className="font-bold text-sm mb-2 text-gray-800 dark:text-gray-100 whitespace-pre-wrap"
                                           dangerouslySetInnerHTML={{ __html: formatPreview(previewHeaderText, sampleHeader) }} />
                                    )}
                                    {previewHeaderType === 'IMAGE' && (
                                        <div className="w-full h-32 bg-gray-200 dark:bg-gray-700 rounded mb-2 flex items-center justify-center overflow-hidden">
                                            {previewHeaderMedia ? <img src={previewHeaderMedia} className="w-full h-full object-cover" /> : <ImageIcon className="w-8 h-8 text-gray-400" />}
                                        </div>
                                    )}
                                    {previewHeaderType === 'VIDEO' && (
                                        <div className="w-full h-32 bg-gray-200 dark:bg-gray-700 rounded mb-2 flex items-center justify-center overflow-hidden">
                                            {previewHeaderMedia ? <video src={previewHeaderMedia} className="w-full h-full object-cover" /> : <Video className="w-8 h-8 text-gray-400" />}
                                        </div>
                                    )}
                                    {previewHeaderType === 'DOCUMENT' && (
                                        <div className="w-full p-2 bg-gray-100 dark:bg-gray-800 rounded mb-2 flex items-center border border-gray-200 dark:border-gray-700">
                                            <div className="w-8 h-8 bg-red-100 text-red-500 rounded flex items-center justify-center mr-2">
                                                <FileText className="w-5 h-5" />
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <p className="text-xs font-medium truncate dark:text-gray-200">document.pdf</p>
                                                <p className="text-[10px] text-gray-500">PDF Document</p>
                                            </div>
                                        </div>
                                    )}

                                    {/* Body Preview */}
                                    {previewBodyText ? (
                                        <p className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-words"
                                           dangerouslySetInnerHTML={{ __html: formatPreview(previewBodyText, sampleBody) }} />
                                    ) : (
                                        <p className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-words">
                                            Pesan Anda...
                                        </p>
                                    )}

                                    {/* Footer Preview */}
                                    {previewFooterText && (
                                        <p className="text-[11px] text-gray-500 mt-2 leading-tight"
                                           dangerouslySetInnerHTML={{ __html: formatPreview(previewFooterText, []) }} />
                                    )}
                                </div>
                                
                                {/* Buttons Preview */}
                                {previewButtons && previewButtons.length > 0 && (
                                    <div className="flex flex-col gap-1 w-[95%] self-start">
                                        {previewButtons.map((btn, idx) => (
                                            <div key={idx} className="bg-white dark:bg-[#202c33] text-[#00a884] dark:text-[#00a884] font-medium text-xs py-2 px-3 text-center rounded-lg shadow-sm w-full border border-gray-100 dark:border-gray-800">
                                                {btn.text || "Tombol"}
                                            </div>
                                        ))}
                                    </div>
                                )}
                                </div>
                            </div>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
