"use client"

import { ChevronDown } from 'lucide-react';
import React, { useState } from 'react';

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';
import { ObjectFieldTemplateProps } from '@rjsf/utils';

/**
 * Object field template for JSON Schema Form
 *
 * Supports:
 * - Collapsible groups via ui:collapsible option
 * - Grid layout via ui:grid option
 * - Custom styling via ui:className
 *
 * Usage in uiSchema:
 * ```json
 * {
 *   "colors": {
 *     "ui:collapsible": true,
 *     "ui:collapsed": false,
 *     "ui:grid": 2
 *   }
 * }
 * ```
 */
export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
  const {
    title,
    description,
    properties,
    required,
    uiSchema,
  } = props;

  // UI options
  const isCollapsible = uiSchema?.['ui:collapsible'] === true;
  const defaultCollapsed = uiSchema?.['ui:collapsed'] === true;
  const gridCols = uiSchema?.['ui:grid'] as number | undefined;
  const className = uiSchema?.['ui:className'] as string | undefined;

  // Collapsible state
  const [isOpen, setIsOpen] = useState(!defaultCollapsed);

  // Check if this is root object (no title usually means root)
  const isRoot = !title;

  // Grid class based on columns
  const gridClass = gridCols
    ? `grid gap-4 grid-cols-${gridCols}`
    : 'space-y-4';

  // Content wrapper
  const content = (
    <div className={cn(gridClass, className)}>
      {properties.map((element) => (
        <div key={element.name} className="property-wrapper">
          {element.content}
        </div>
      ))}
    </div>
  );

  // Root object - no wrapper
  if (isRoot) {
    return <div className="space-y-6">{content}</div>;
  }

  // Collapsible group
  if (isCollapsible) {
    return (
      <Collapsible open={isOpen} onOpenChange={setIsOpen} className="space-y-2">
        <CollapsibleTrigger className="flex w-full items-center justify-between rounded-lg border bg-muted/50 px-4 py-3 text-left hover:bg-muted transition-colors">
          <div>
            <h3 className="text-sm font-semibold">
              {title}
              {required && <span className="text-destructive ml-1">*</span>}
            </h3>
            {description && (
              <p className="text-xs text-muted-foreground mt-0.5">{description}</p>
            )}
          </div>
          <ChevronDown
            className={cn(
              'h-4 w-4 text-muted-foreground transition-transform duration-200',
              isOpen && 'rotate-180'
            )}
          />
        </CollapsibleTrigger>
        <CollapsibleContent className="pl-1 pr-1 pt-2">
          {content}
        </CollapsibleContent>
      </Collapsible>
    );
  }

  // Regular group with title
  return (
    <div className="space-y-4">
      {title && (
        <div className="border-b pb-2">
          <h3 className="text-sm font-semibold">
            {title}
            {required && <span className="text-destructive ml-1">*</span>}
          </h3>
          {description && (
            <p className="text-xs text-muted-foreground mt-1">{description}</p>
          )}
        </div>
      )}
      {content}
    </div>
  );
}
