"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import {
    Save,
    ArrowLeft,
    Info,
    Copy,
    Check,
    Loader2,
    Plus,
    Trash2,
    Phone,
    Link as LinkIcon,
    MessageSquareReply,
    Send
} from "lucide-react"
import { useToaster } from "@/context/ToasterContext"
import {
    useGetTemplateDraftById,
    useCreateTemplateDraft,
    useUpdateTemplateDraft,
    useSubmitTemplateDraft,
} from "@/lib/react-query/hooks/whatsapp"
import {
    TemplateDraftItem,
    TemplateDraftButton,
    TemplatePlaceholder,
    CreateTemplateDraftPayload
} from "@/types/whatsapp"

const PLACEHOLDER_TYPES = [
    { value: "customer_name", label: "Client full name" },
    { value: "appointment_date", label: "Booking date" },
    { value: "appointment_time", label: "Booking time" },
    { value: "appointment_datetime", label: "Booking date & time" },
    { value: "service_name", label: "Booked service name" },
    { value: "salon_name", label: "Salon name" },
    { value: "stylist_name", label: "Assigned stylist name" },
    { value: "salon_address", label: "Salon full address" },
    { value: "booking_id", label: "Unique booking ID" },
    { value: "total_amount", label: "Total appointment cost" },
    { value: "payment_status", label: "Payment status" },
    { value: "payment_method", label: "Payment method" },
    { value: "contact_phone", label: "Client phone number" },
    { value: "cancellation_link", label: "Cancellation link" },
    { value: "reschedule_link", label: "Reschedule link" },
    { value: "maps_link", label: "Google Maps link" },
    { value: "special_instructions", label: "Special instructions" },
    { value: "appointment_duration", label: "Service duration" },
    { value: "discount_amount", label: "Discount amount" },
    { value: "final_amount", label: "Final amount" },
    { value: "currency", label: "Currency code" },
    { value: "support_phone", label: "Salon support phone" },
    { value: "support_email", label: "Salon support email" },
    { value: "branch_name", label: "Salon branch name" },
    { value: "city", label: "City" },
    { value: "country", label: "Country" },
    { value: "timezone", label: "Salon timezone" },
    { value: "invoice_link", label: "Invoice PDF link" },
]

const PLACEHOLDER_EXAMPLES: Record<string, string> = {
    customer_name: "Amit",
    appointment_date: "26 Feb 2026",
    appointment_time: "10:30",
    appointment_datetime: "26 Feb 2026",
    service_name: "Haircut",
    salon_name: "Aivly",
    stylist_name: "John",
    salon_address: "123 Main St, City",
    booking_id: "#BK12345",
    total_amount: "500",
    payment_status: "Paid",
    payment_method: "UPI",
    contact_phone: "+919876543210",
    cancellation_link: "https://aivly.com/cancel",
    reschedule_link: "https://aivly.com/reschedule",
    maps_link: "https://maps.google.com",
    special_instructions: "None",
    appointment_duration: "30",
    discount_amount: "50",
    final_amount: "450",
    currency: "INR",
    support_phone: "+19876543210",
    support_email: "support@aivly.com",
    branch_name: "Downtown",
    city: "Mohali",
    country: "India",
    timezone: "IST",
    invoice_link: "https://aivly.com/invoice",
}

const BUTTON_TYPES = [
    { value: "PHONE_NUMBER", label: "Phone Number", icon: Phone },
    { value: "URL", label: "URL", icon: LinkIcon },
    { value: "QUICK_REPLY", label: "Quick Reply", icon: MessageSquareReply },
]

interface TemplateDraftEditorProps {
    templateId?: string | null
    onBack: () => void
}

export function WhatsAppTemplateDraftEditor({ templateId, onBack }: TemplateDraftEditorProps) {
    const { data: existingTemplate, isLoading: isLoadingTemplate } = useGetTemplateDraftById(templateId || "")
    const createDraft = useCreateTemplateDraft()
    const updateDraft = useUpdateTemplateDraft()
    const submitDraft = useSubmitTemplateDraft()
    const { showInfo } = useToaster()

    const [name, setName] = useState("aivly_booking_confirmation")
    const [body, setBody] = useState("Hi {{1}}, your booking at Aivly has been confirmed for {{2}}. We look forward to serving you.")
    const [header, setHeader] = useState("Aivly Booking Confirmation")
    const [footer, setFooter] = useState("Reply STOP to unsubscribe")
    const [category, setCategory] = useState("UTILITY")
    const [language, setLanguage] = useState("en_US")
    const [buttons, setButtons] = useState<TemplateDraftButton[]>([
        { type: "PHONE_NUMBER", text: "Call Support", phone_number: "+19876543210" },
    ])
    const [placeholders, setPlaceholders] = useState<TemplatePlaceholder[]>([
        { key: "{{1}}", valueType: "customer_name", example: "Amit" },
        { key: "{{2}}", valueType: "appointment_datetime", example: "26 Feb 2026" },
    ])
    const [copiedVar, setCopiedVar] = useState<string | null>(null)

    const isEditMode = !!templateId

    useEffect(() => {
        if (existingTemplate && isEditMode) {
            setName(existingTemplate.internalName || existingTemplate.name || "")
            setBody(existingTemplate.messageBody || existingTemplate.body || "")
            setHeader(existingTemplate.headerText || existingTemplate.header || "")
            setFooter(existingTemplate.footerText || existingTemplate.footer || "")
            setCategory(existingTemplate.category || "UTILITY")
            setLanguage(existingTemplate.language || "en_US")
            setButtons(existingTemplate.buttons || [])

            const mappedPlaceholders = (existingTemplate.placeholders || []).map((p: any) => ({
                key: p.key,
                valueType: p.valueType || p.type || "",
                example: p.example || ""
            }))
            setPlaceholders(mappedPlaceholders)
        }
    }, [existingTemplate, isEditMode])

    const handleCopyVariable = (key: string) => {
        navigator.clipboard.writeText(key)
        setCopiedVar(key)
        setTimeout(() => setCopiedVar(null), 2000)
        showInfo(`Copied ${key} to clipboard`)
    }

    const addButton = () => {
        setButtons([...buttons, { type: "QUICK_REPLY", text: "" }])
    }

    const updateButton = (index: number, field: keyof TemplateDraftButton, value: string) => {
        const updated = [...buttons]
        updated[index] = { ...updated[index], [field]: value }
        setButtons(updated)
    }

    const removeButton = (index: number) => {
        setButtons(buttons.filter((_, i) => i !== index))
    }

    const addPlaceholder = () => {
        const nextKey = `{{${placeholders.length + 1}}}`
        setPlaceholders([...placeholders, { key: nextKey, valueType: "customer_name", example: PLACEHOLDER_EXAMPLES["customer_name"] }])
    }

    const updatePlaceholder = (index: number, field: keyof TemplatePlaceholder, value: string) => {
        const updated = [...placeholders]
        if (field === "valueType") {
            updated[index] = { ...updated[index], [field]: value, example: PLACEHOLDER_EXAMPLES[value] || "" }
        } else {
            updated[index] = { ...updated[index], [field]: value }
        }
        setPlaceholders(updated)
    }

    const removePlaceholder = (index: number) => {
        setPlaceholders(placeholders.filter((_, i) => i !== index))
    }

    const getPreviewText = (text: string) => {
        let preview = text
        placeholders.forEach((p) => {
            const example = p.example || PLACEHOLDER_EXAMPLES[p.valueType] || p.valueType
            preview = preview.replace(new RegExp(p.key.replace(/[{}]/g, '\\$&'), 'g'), example)
        })
        return preview
    }

    const handleSave = () => {
        const payload: CreateTemplateDraftPayload = {
            name,
            body,
            category,
            language,
            header: header || undefined,
            footer: footer || undefined,
            buttons: buttons.length > 0 ? buttons : undefined,
            placeholders: placeholders.length > 0 ? placeholders : undefined,
        }

        if (isEditMode && templateId) {
            updateDraft.mutate(
                { id: templateId, payload },
                { onSuccess: () => onBack() }
            )
        } else {
            createDraft.mutate(payload, { onSuccess: () => onBack() })
        }
    }

    const isSaving = createDraft.isPending || updateDraft.isPending
    const isSubmitting = submitDraft.isPending

    const handleSubmit = () => {
        if (templateId) {
            submitDraft.mutate(templateId, { onSuccess: () => onBack() })
        }
    }

    if (isEditMode && isLoadingTemplate) {
        return (
            <div className="flex flex-col items-center justify-center min-h-[400px] space-y-4">
                <Loader2 className="w-8 h-8 animate-spin text-primary" />
                <p className="text-muted-foreground animate-pulse">Loading template...</p>
            </div>
        )
    }

    return (
        <div className="space-y-6 animate-fade-in">
            {/* Back button */}
            <div className="flex items-center gap-3">
                <Button
                    variant="ghost"
                    onClick={onBack}
                    className="gap-2 text-gray-600 hover:text-gray-900 px-2"
                >
                    <ArrowLeft className="w-4 h-4" />
                    Back to Templates
                </Button>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Editor Column */}
                <div className="space-y-6">
                    {/* Basic Info */}
                    <Card className="shadow-card border-none bg-white">
                        <CardHeader>
                            <CardTitle className="text-lg font-semibold">
                                {isEditMode ? "Edit Template" : "Create Template"}
                            </CardTitle>
                            <CardDescription>
                                {isEditMode ? "Modify your template draft" : "Set up a new WhatsApp message template"}
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="name" className="text-sm font-medium">Template Name</Label>
                                    <Input
                                        id="name"
                                        value={name}
                                        onChange={(e) => setName(e.target.value)}
                                        placeholder="e.g. Booking Confirmation"
                                        className="bg-gray-50/50 border-gray-200"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="category" className="text-sm font-medium">Category</Label>
                                    <Select value={category} onValueChange={setCategory}>
                                        <SelectTrigger className="bg-gray-50/50 border-gray-200">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="UTILITY">Utility</SelectItem>
                                            <SelectItem value="MARKETING">Marketing</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="language" className="text-sm font-medium">Language</Label>
                                <Select value={language} onValueChange={setLanguage}>
                                    <SelectTrigger className="bg-gray-50/50 border-gray-200 w-full sm:w-48">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="en_US">English (US)</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="header" className="text-sm font-medium">Header Text</Label>
                                <Input
                                    id="header"
                                    value={header}
                                    onChange={(e) => setHeader(e.target.value)}
                                    placeholder="Enter header text"
                                    className="bg-gray-50/50 border-gray-200"
                                />
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="body" className="text-sm font-medium">Message Body</Label>
                                <Textarea
                                    id="body"
                                    value={body}
                                    onChange={(e) => setBody(e.target.value)}
                                    className="min-h-[200px] font-mono text-sm bg-gray-50/50 border-gray-200 resize-none"
                                    placeholder="Enter your message template...&#10;&#10;Use {{1}}, {{2}}, etc. as placeholders"
                                />
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="footer" className="text-sm font-medium">Footer Text</Label>
                                <Input
                                    id="footer"
                                    value={footer}
                                    onChange={(e) => setFooter(e.target.value)}
                                    placeholder="Enter footer text"
                                    className="bg-gray-50/50 border-gray-200"
                                />
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="shadow-card border-none bg-white">
                        <CardHeader>
                            <div className="flex items-center justify-between">
                                <div>
                                    <CardTitle className="text-lg font-semibold flex items-center gap-2">
                                        <Info className="w-5 h-5 text-stat-blue" />
                                        Placeholders
                                    </CardTitle>
                                    <CardDescription>
                                        Map template variables to data fields
                                    </CardDescription>
                                </div>
                                {placeholders.length < 2 && (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={addPlaceholder}
                                        className="gap-1 text-xs"
                                    >
                                        <Plus className="w-3 h-3" />
                                        Add
                                    </Button>
                                )}
                            </div>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {placeholders.length === 0 ? (
                                <p className="text-sm text-muted-foreground text-center py-4">
                                    No placeholders added yet. Click &quot;Add&quot; to map variables.
                                </p>
                            ) : (
                                placeholders.map((p, index) => (
                                    <div key={index} className="flex items-center gap-3 p-3 bg-gray-50/80 rounded-lg">
                                        <Badge
                                            variant="secondary"
                                            className="cursor-pointer hover:bg-stat-blue-bg transition-colors py-1.5 px-3 bg-gray-100/80 text-gray-700 border-none shrink-0"
                                            onClick={() => handleCopyVariable(p.key)}
                                        >
                                            {copiedVar === p.key ? (
                                                <Check className="w-3 h-3 mr-1 text-stat-emerald" />
                                            ) : (
                                                <Copy className="w-3 h-3 mr-1 opacity-50" />
                                            )}
                                            {p.key}
                                        </Badge>
                                        <Select
                                            value={p.valueType}
                                            onValueChange={(val) => updatePlaceholder(index, "valueType", val)}
                                        >
                                            <SelectTrigger className="flex-1 bg-white border-gray-200 text-sm h-9">
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {PLACEHOLDER_TYPES.map((pt) => (
                                                    <SelectItem key={pt.value} value={pt.value}>
                                                        {pt.label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => removePlaceholder(index)}
                                            className="shrink-0 text-gray-400 hover:text-red-500 p-1 h-auto"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </Button>
                                    </div>
                                ))
                            )}
                        </CardContent>
                    </Card>

                    <Card className="shadow-card border-none bg-white">
                        <CardHeader>
                            <div className="flex items-center justify-between">
                                <div>
                                    <CardTitle className="text-lg font-semibold">Action Buttons</CardTitle>
                                    <CardDescription>
                                        Add interactive buttons to your template (max 2)
                                    </CardDescription>
                                </div>
                                {buttons.length < 3 && (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={addButton}
                                        className="gap-1 text-xs"
                                    >
                                        <Plus className="w-3 h-3" />
                                        Add Button
                                    </Button>
                                )}
                            </div>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            {buttons.length === 0 ? (
                                <p className="text-sm text-muted-foreground text-center py-4">
                                    No buttons added. Add up to 3 interactive buttons.
                                </p>
                            ) : (
                                buttons.map((btn, index) => {
                                    const BtnTypeInfo = BUTTON_TYPES.find(bt => bt.value === btn.type)
                                    const BtnIcon = BtnTypeInfo?.icon || MessageSquareReply
                                    return (
                                        <div key={index} className="p-4 bg-gray-50/80 rounded-lg space-y-3 border border-gray-100">
                                            <div className="flex items-center justify-between">
                                                <div className="flex items-center gap-2">
                                                    <BtnIcon className="w-4 h-4 text-primary" />
                                                    <span className="text-sm font-medium text-gray-700">Button {index + 1}</span>
                                                </div>
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() => removeButton(index)}
                                                    className="text-gray-400 hover:text-red-500 p-1 h-auto"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </Button>
                                            </div>

                                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-muted-foreground">Type</Label>
                                                    <Select
                                                        value={btn.type}
                                                        onValueChange={(val) => updateButton(index, "type", val)}
                                                    >
                                                        <SelectTrigger className="bg-white border-gray-200 h-9 text-sm">
                                                            <SelectValue />
                                                        </SelectTrigger>
                                                        <SelectContent>
                                                            {BUTTON_TYPES.map((bt) => (
                                                                <SelectItem key={bt.value} value={bt.value}>
                                                                    {bt.label}
                                                                </SelectItem>
                                                            ))}
                                                        </SelectContent>
                                                    </Select>
                                                </div>
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-muted-foreground">Button Text</Label>
                                                    <Input
                                                        value={btn.text}
                                                        onChange={(e) => updateButton(index, "text", e.target.value)}
                                                        placeholder="Button label"
                                                        className="bg-white border-gray-200 h-9 text-sm"
                                                    />
                                                </div>
                                            </div>

                                            {btn.type === "PHONE_NUMBER" && (
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-muted-foreground">Phone Number</Label>
                                                    <Input
                                                        value={btn.phone_number || ""}
                                                        onChange={(e) => updateButton(index, "phone_number", e.target.value)}
                                                        placeholder="+911721234567"
                                                        className="bg-white border-gray-200 h-9 text-sm"
                                                    />
                                                </div>
                                            )}

                                            {btn.type === "URL" && (
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-muted-foreground">URL</Label>
                                                    <Input
                                                        value={btn.url || ""}
                                                        onChange={(e) => updateButton(index, "url", e.target.value)}
                                                        // placeholder="https://yourshop.com/track/{{2}}"
                                                        className="bg-white border-gray-200 h-9 text-sm"
                                                    />
                                                </div>
                                            )}

                                            {btn.type === "QUICK_REPLY" && (
                                                <div className="space-y-1">
                                                    <Label className="text-xs text-muted-foreground">Payload</Label>
                                                    <Input
                                                        value={btn.payload || ""}
                                                        onChange={(e) => updateButton(index, "payload", e.target.value)}
                                                        placeholder="cancel_order"
                                                        className="bg-white border-gray-200 h-9 text-sm"
                                                    />
                                                </div>
                                            )}
                                        </div>
                                    )
                                })
                            )}
                        </CardContent>
                    </Card>

                    <div className="flex gap-3">
                        <Button
                            onClick={handleSave}
                            className="flex-1 gap-2 bg-primary-gradient text-white h-12"
                            disabled={isSaving || isSubmitting || !name.trim() || !body.trim()}
                        >
                            {isSaving ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                                <Save className="w-4 h-4" />
                            )}
                            {isSaving ? "Saving..." : isEditMode ? "Update Template" : "Create Template"}
                        </Button>
                        {isEditMode && existingTemplate?.status === "DRAFT" && (
                            <Button
                                onClick={handleSubmit}
                                variant="outline"
                                className="gap-2 border-emerald-500 text-emerald-600 hover:bg-emerald-50 h-12 px-6"
                                disabled={isSubmitting || isSaving}
                            >
                                {isSubmitting ? (
                                    <Loader2 className="w-4 h-4 animate-spin" />
                                ) : (
                                    <Send className="w-4 h-4" />
                                )}
                                {isSubmitting ? "Submitting..." : "Submit"}
                            </Button>
                        )}
                    </div>
                </div>

                <div className="lg:sticky lg:top-6 self-start">
                    <Card className="shadow-card border-none bg-white">
                        <CardHeader>
                            <CardTitle className="text-lg font-semibold">Live Preview</CardTitle>
                            <CardDescription>
                                See how your message will appear on WhatsApp
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="phone-mockup mx-auto max-w-[320px]">
                                <div className="bg-whatsapp-bg h-full overflow-hidden">
                                    <div className="bg-whatsapp-green px-4 py-3 flex items-center gap-3 pt-8">
                                        <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                                            <span className="text-white font-bold">HR</span>
                                        </div>
                                        <div>
                                            <p className="text-white font-semibold text-sm">Hair Raizers 91</p>
                                            <p className="text-white/80 text-xs">Business Account</p>
                                        </div>
                                    </div>

                                    <div className="p-4 min-h-[450px] space-y-3">
                                        {header && (
                                            <div className="text-center">
                                                <span className="text-[11px] bg-white/90 text-gray-600 px-3 py-1 rounded-full shadow-sm">
                                                    {getPreviewText(header)}
                                                </span>
                                            </div>
                                        )}

                                        <div className="whatsapp-bubble ml-0 mr-8">
                                            <div className="text-sm text-gray-900 whitespace-pre-wrap leading-relaxed">
                                                {body ? (
                                                    getPreviewText(body).split(/(https?:\/\/[^\s]+)/g).map((part, i) => {
                                                        if (part.match(/https?:\/\/[^\s]+/)) {
                                                            return <span key={i} className="text-blue-500 hover:underline">{part}</span>
                                                        }
                                                        return part
                                                    })
                                                ) : (
                                                    <span className="text-gray-400 italic">Your message preview will appear here...</span>
                                                )}
                                            </div>
                                            <div className="flex items-center justify-end gap-1 mt-1">
                                                <p className="text-[10px] text-gray-400">10:30</p>
                                                <span className="text-blue-500 text-[10px]">✓✓</span>
                                            </div>
                                        </div>

                                        {buttons.length > 0 && (
                                            <div className="space-y-2 mr-8">
                                                {buttons.map((btn, i) => (
                                                    <button
                                                        key={i}
                                                        className="w-full text-stat-emerald text-sm font-medium py-2.5 bg-white rounded-lg shadow-sm flex items-center justify-center gap-2 border border-gray-100"
                                                    >
                                                        {btn.text || `Button ${i + 1}`}
                                                    </button>
                                                ))}
                                            </div>
                                        )}

                                        {footer && (
                                            <p className="text-[11px] text-center text-gray-500 mt-6 bg-white/30 backdrop-blur-sm py-1 rounded">
                                                {footer}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    )
}
