import * as React from "react"
import { Search, Hash, Type } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog"
import { SettingInput, SafeRender, ModernCardHeader } from "./settings-ui"

interface PersonalizationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onInsert: (placeholder: string) => void
  placeholders: Record<string, string>
  triggerKey?: string
}

export function PersonalizationDialog({
  open,
  onOpenChange,
  onInsert,
  placeholders,
  triggerKey,
}: PersonalizationDialogProps) {
  const [search, setSearch] = React.useState("")

  const filteredPlaceholders = React.useMemo(() => {
    const isWordPress = triggerKey?.startsWith('user_');
    const isWooCommerce = triggerKey?.includes('wc_status_') || triggerKey?.includes('wc_order_') || triggerKey?.includes('wc_sub_');
    const isSubscriptions = triggerKey?.includes('wc_sub_');

    // 1. Categorize the flat placeholders
    const categorized: Record<string, Record<string, string>> = {
      "General Site Variables": {},
      "WordPress User Accounts": {},
      "WooCommerce Order Details": {},
      "WooCommerce Items & Products": {},
      "WooCommerce Billing & Shipping": {},
      "WooCommerce Subscriptions": {},
    };

    Object.entries(placeholders).forEach(([key, label]) => {
      if (key.startsWith('{{wp-') || key.includes('user_')) {
        categorized["WordPress User Accounts"][key] = label;
      } else if (key.startsWith('{{wc-order') || key.startsWith('{{order_') || key.startsWith('{{status}}') || key.startsWith('{{payment_') || key.startsWith('{{shipping_method') || key.startsWith('{{transaction_id') || key.startsWith('{{cust_note')) {
        categorized["WooCommerce Order Details"][key] = label;
      } else if (key.startsWith('{{wc-product') || key.startsWith('{{product}}') || key.startsWith('{{wc-sku')) {
        categorized["WooCommerce Items & Products"][key] = label;
      } else if (key.startsWith('{{billing_') || key.startsWith('{{shipping_')) {
        categorized["WooCommerce Billing & Shipping"][key] = label;
      } else if (key.startsWith('{{subscription_') || key.startsWith('{{next_payment_') || key.startsWith('{{renewal_')) {
        categorized["WooCommerce Subscriptions"][key] = label;
      } else {
        categorized["General Site Variables"][key] = label;
      }
    });

    const result: Record<string, Record<string, string>> = {}
    
    Object.entries(categorized).forEach(([group, items]) => {
      // 🚨 Filtering Logic based on trigger:
      const groupLower = group.toLowerCase();
      let shouldShowGroup = false;

      if (groupLower.includes('general')) shouldShowGroup = true;
      else if (isSubscriptions) shouldShowGroup = true;
      else if (isWooCommerce) {
          if (!groupLower.includes('subscription')) shouldShowGroup = true;
      } else if (isWordPress) {
          if (groupLower.includes('wordpress')) shouldShowGroup = true;
      } else {
          shouldShowGroup = true; // Fallback
      }

      if (!shouldShowGroup) return;

      const filteredItems: Record<string, string> = {}
      Object.entries(items).forEach(([key, label]) => {
        if (
          (label || "").toLowerCase().includes(search.toLowerCase()) ||
          (key || "").toLowerCase().includes(search.toLowerCase())
        ) {
          filteredItems[key] = label
        }
      })

      if (Object.keys(filteredItems).length > 0) {
        result[group] = filteredItems
      }
    });

    return result
  }, [placeholders, search, triggerKey])

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent overlayClassName="z-[200000]" className="max-w-2xl p-0 overflow-hidden gap-0 z-[200001]">
        <DialogTitle className="sr-only">Personalization</DialogTitle>
        <DialogDescription className="sr-only">Insert dynamic variables to customize your message for each recipient</DialogDescription>
        <ModernCardHeader 
          title="Personalization"
          description="Insert dynamic variables to customize your message for each recipient"
          icon={Type}
        />

        <div className="p-4 border-b">
          <div className="w-full text-left">
            <SettingInput
              label="Search variables"
              placeholder="Search variables..."
              value={search}
              onChange={setSearch}
              icon={Search}
              className="h-11 bg-white border-slate-200"
              labelHidden
            />
          </div>
        </div>

        <div className="max-h-[400px] overflow-y-auto border-t bg-slate-50/10">
          <div className="px-1 py-4 space-y-4">
            {Object.entries(filteredPlaceholders).map(([group, items]) => (
              <div key={group} className="space-y-1">
                <h3 className="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-4 mb-2">
                  {group}
                </h3>
                <div className="space-y-0.5">
                  {Object.entries(items).map(([key, label]) => (
                    <button
                      key={key}
                      onClick={() => {
                        onInsert(key)
                        onOpenChange(false)
                      }}
                      className="w-full flex items-center justify-between px-4 py-2.5 hover:bg-slate-50 transition-colors text-left group"
                    >
                      <div className="flex items-center gap-3">
                        <Hash className="w-3.5 h-3.5 text-slate-300 group-hover:text-primary transition-colors" />
                        <span className="text-sm font-medium text-slate-700">
                          <SafeRender content={label} />
                        </span>
                      </div>
                      <span className="text-[10px] font-mono font-medium text-slate-400 group-hover:text-primary transition-colors">
                        {key}
                      </span>
                    </button>
                  ))}
                </div>
              </div>
            ))}
            {Object.keys(filteredPlaceholders).length === 0 && (
              <div className="flex flex-col items-center justify-center py-12 text-slate-400">
                <Type className="w-12 h-12 mb-3 opacity-20" />
                <p className="text-sm">No variables found for your search.</p>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
