import React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Plus, Trash2, GripVertical } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { MediaUploader } from '@/components/MediaUploader';
import RepeaterProductField from './RepeaterProductField';

interface RepeaterFieldDef {
  name: string;
  label: string;
  type: 'text' | 'textarea' | 'url' | 'image' | 'icon' | 'product';
  placeholder?: string;
}

interface InspectorRepeaterProps {
  label: string;
  items: any[];
  fields: RepeaterFieldDef[];
  onChange: (items: any[]) => void;
  itemLabelKey?: string; // Key to use for the accordion header (e.g., 'title')
  isDynamic?: boolean; // If true, items come from a dynamic source — hide Add Item
  dynamicLabel?: string; // Custom label for the dynamic placeholder
}

function SortableItem({
  id,
  item,
  index,
  fields,
  itemLabelKey,
  onChange,
  onDelete,
}: any) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  // List of available icons for selection
  const ICON_OPTIONS = [
    'Star', 'Zap', 'Shield', 'Heart', 'Award', 'Clock', 'User', 'Settings',
    'Check', 'X', 'ArrowRight', 'Mail', 'Phone', 'MapPin', 'Briefcase',
    'Calendar', 'Camera', 'Cloud', 'Code', 'Cpu', 'CreditCard', 'Database',
    'DollarSign', 'Eye', 'File', 'Folder', 'Globe', 'Home', 'Image',
    'Layers', 'Layout', 'LifeBuoy', 'Link', 'Lock', 'MessageCircle',
    'Monitor', 'Moon', 'Music', 'Package', 'PieChart', 'Play', 'Power',
    'Printer', 'Radio', 'Search', 'Server', 'ShoppingBag', 'ShoppingCart',
    'Smartphone', 'Speaker', 'Sun', 'Tablet', 'Tag', 'Terminal', 'Tool',
    'Truck', 'Tv', 'Umbrella', 'Upload', 'Video', 'Voicemail', 'Volume2',
    'Wifi', 'Wrench',
  ].sort();

  const handleFieldChange = (fieldName: string, value: any) => {
    onChange(index, fieldName, value);
  };

  return (
    <div ref={setNodeRef} style={style} className="bg-white border rounded-md mb-2">
      <AccordionItem value={`item-${index}`} className="border-0">
        <div className="flex items-center gap-2 px-3 py-2 border-b bg-gray-50/50 rounded-t-md">
          <button
            {...attributes}
            {...listeners}
            className="cursor-grab text-gray-400 hover:text-gray-600"
          >
            <GripVertical className="w-4 h-4" />
          </button>

          <AccordionTrigger className="hover:no-underline py-0 flex-1 text-sm font-medium">
            {item[itemLabelKey] || `Item ${index + 1}`}
          </AccordionTrigger>

          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6 text-gray-400 hover:text-red-500"
            onClick={(e: any) => {
              e.stopPropagation();
              onDelete(index);
            }}
          >
            <Trash2 className="w-3 h-3" />
          </Button>
        </div>

        <AccordionContent className="p-3 space-y-3">
          {fields.map((field: RepeaterFieldDef) => (
            <RepeaterFieldRenderer
              key={field.name}
              field={field}
              item={item}
              index={index}
              onChange={handleFieldChange}
              ICON_OPTIONS={ICON_OPTIONS}
            />
          ))}
        </AccordionContent>
      </AccordionItem>
    </div>
  );
}

function RepeaterFieldRenderer({
  field,
  item,
  index,
  onChange,
  ICON_OPTIONS,
}: {
  field: RepeaterFieldDef;
  item: any;
  index: number;
  onChange: (fieldName: string, value: any) => void;
  ICON_OPTIONS: string[];
}) {
  const value = item[field.name] || '';

  if (field.type === 'textarea') {
    return (
      <div className="space-y-1.5">
        <Label className="text-xs text-gray-500">{field.label}</Label>
        <Textarea
          value={value}
          onChange={(e) => onChange(field.name, e.target.value)}
          placeholder={field.placeholder}
          className="text-xs min-h-[60px]"
        />
      </div>
    );
  }

  if (field.type === 'icon') {
    return (
      <div className="space-y-1.5">
        <Label className="text-xs text-gray-500">{field.label}</Label>
        <Select
          value={value}
          onValueChange={(val) => onChange(field.name, val)}
        >
          <SelectTrigger className="h-8 text-xs w-full">
            <SelectValue placeholder="Select an icon" />
          </SelectTrigger>
          <SelectContent className="max-h-[200px]">
            {ICON_OPTIONS.map((iconName) => (
              <SelectItem key={iconName} value={iconName}>
                <div className="flex items-center gap-2">
                  <span>{iconName}</span>
                </div>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    );
  }

  if (field.type === 'image') {
    return (
      <div className="space-y-1.5">
        <Label className="text-xs text-gray-500">{field.label}</Label>
        <div className="space-y-2">
          {value ? (
            <MediaUploader
              onSelect={(url) => onChange(field.name, url)}
              type="image"
            >
              <div className="relative group cursor-pointer border rounded overflow-hidden h-24 bg-gray-50 flex items-center justify-center">
                <img src={value} alt={field.label} className="w-full h-full object-cover" />
                <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                  <span className="text-white text-xs font-medium">Change</span>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onChange(field.name, '');
                  }}
                  className="absolute top-1 right-1 bg-white/90 p-1 rounded-full text-gray-600 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
                  type="button"
                  aria-label="Remove image"
                >
                  <Trash2 className="w-3 h-3" />
                </button>
              </div>
            </MediaUploader>
          ) : (
            <MediaUploader
              onSelect={(url) => onChange(field.name, url)}
              type="image"
            >
              <Button variant="outline" className="w-full h-24 border-dashed flex flex-row gap-2 text-gray-400 font-normal justify-start">
                Select Image
              </Button>
            </MediaUploader>
          )}
        </div>
      </div>
    );
  }

  if (field.type === 'product') {
    return (
      <RepeaterProductField
        label={field.label}
        value={item.product_slug || value || ''}
        onChange={(fieldName, nextValue) => {
          // fieldName is expected to be one of the product_* keys.
          onChange(fieldName, nextValue);
        }}
      />
    );
  }

  // default: text/url inputs
  const inputType = field.type === 'url' ? 'url' : 'text';

  return (
    <div key={field.name} className="space-y-1.5">
      <Label className="text-xs text-gray-500">{field.label}</Label>
      <Input
        type={inputType}
        value={value}
        onChange={(e) => onChange(field.name, e.target.value)}
        placeholder={field.placeholder}
        className="h-8 text-xs"
      />
    </div>
  );
}

export function InspectorRepeater({
  label,
  items = [],
  fields,
  onChange,
  itemLabelKey = 'title',
  isDynamic = false,
  dynamicLabel,
}: InspectorRepeaterProps) {
  const itemIds = items.map((_, i) => `item-${i}`);

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    }),
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (over && active.id !== over.id) {
      const oldIndex = itemIds.indexOf(active.id as string);
      const newIndex = itemIds.indexOf(over.id as string);
      onChange(arrayMove(items, oldIndex, newIndex));
    }
  };

  const handleItemChange = (index: number, fieldName: string, value: string) => {
    const newItems = [...items];
    newItems[index] = { ...newItems[index], [fieldName]: value };
    onChange(newItems);
  };

  const handleAddItem = () => {
    const newItem: any = {};
    fields.forEach((f) => (newItem[f.name] = ''));
    onChange([...items, newItem]);
  };

  const handleDeleteItem = (index: number) => {
    const newItems = [...items];
    newItems.splice(index, 1);
    onChange(newItems);
  };

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <Label className="text-xs font-semibold text-gray-500 uppercase tracking-wider">{label}</Label>
        {!isDynamic && (
          <Button variant="outline" size="sm" className="h-6 text-xs" onClick={handleAddItem}>
            <Plus className="w-3 h-3 mr-1" />
            Add Item
          </Button>
        )}
      </div>

      <Accordion type="single" collapsible className="w-full">
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <SortableContext items={itemIds} strategy={verticalListSortingStrategy}>
            {items.map((item, index) => (
              <SortableItem
                key={`item-${index}`}
                id={`item-${index}`}
                index={index}
                item={item}
                fields={fields}
                itemLabelKey={itemLabelKey}
                onChange={(idx: number, fieldName: string, value: string) => handleItemChange(idx, fieldName, value)}
                onDelete={handleDeleteItem}
              />
            ))}
          </SortableContext>
        </DndContext>
      </Accordion>

      {items.length === 0 && (
        <div
          className={cn(
            'text-xs text-center py-4 border rounded-md',
            isDynamic
              ? 'text-blue-600 border-blue-200 bg-blue-50'
              : 'text-gray-400 border-dashed bg-gray-50',
          )}
        >
          {isDynamic
            ? dynamicLabel || '⚡ Auto-populated from related posts at runtime'
            : 'No items yet. Click "Add Item" to start.'}
        </div>
      )}
    </div>
  );
}
