import { type ReactElement, useMemo } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";

/**
 * Field — shadcn/WealthX
 * Base: npx shadcn\@latest add field
 * Figma: https://www.figma.com/design/9V9F0NGVsif8LGmEhVjOcT/Design-System---shadcn?node-id=1188-4205
 *
 * WealthX additions:
 *   - FieldDescription/FieldError: text-xs (12px) per Figma helper text spec
 *   - FieldError.uniqueErrors: Array.from() instead of spread on Map iterator (es5 compat)
 */

export type FieldSetProps = React.ComponentProps<"fieldset">;

function FieldSet({ className, ...props }: FieldSetProps): ReactElement {
  return (
    <fieldset
      className={cn(
        "flex flex-col gap-6",
        "has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
        className
      )}
      data-slot="field-set"
      {...props}
    />
  );
}

export type FieldLegendProps = React.ComponentProps<"legend"> & {
  variant?: "legend" | "label";
};

function FieldLegend({
  className,
  variant = "legend",
  ...props
}: FieldLegendProps): ReactElement {
  return (
    <legend
      className={cn(
        "mb-3",
        "data-[variant=legend]:text-label-large",
        "data-[variant=label]:text-label-medium",
        className
      )}
      data-slot="field-legend"
      data-variant={variant}
      {...props}
    />
  );
}

export type FieldGroupProps = React.ComponentProps<"div">;

function FieldGroup({ className, ...props }: FieldGroupProps): ReactElement {
  return (
    <div
      className={cn(
        "group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
        className
      )}
      data-slot="field-group"
      {...props}
    />
  );
}

const fieldVariants = cva(
  "group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
  {
    variants: {
      orientation: {
        vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
        horizontal: [
          "flex-row items-center",
          "[&>[data-slot=field-label]]:flex-auto",
          "has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
        ],
        responsive: [
          "flex-col @md/field-group:flex-row @md/field-group:items-center [&>*]:w-full @md/field-group:[&>*]:w-auto [&>.sr-only]:w-auto",
          "@md/field-group:[&>[data-slot=field-label]]:flex-auto",
          "@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
        ],
      },
    },
    defaultVariants: {
      orientation: "vertical",
    },
  }
);

export type FieldProps = React.ComponentProps<"div"> &
  VariantProps<typeof fieldVariants>;

function Field({
  className,
  orientation = "vertical",
  ...props
}: FieldProps): ReactElement {
  return (
    <div
      className={cn(fieldVariants({ orientation }), className)}
      data-orientation={orientation}
      data-slot="field"
      role="group"
      {...props}
    />
  );
}

export type FieldContentProps = React.ComponentProps<"div">;

function FieldContent({
  className,
  ...props
}: FieldContentProps): ReactElement {
  return (
    <div
      className={cn(
        "group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
        className
      )}
      data-slot="field-content"
      {...props}
    />
  );
}

export type FieldLabelProps = React.ComponentProps<typeof Label>;

function FieldLabel({ className, ...props }: FieldLabelProps): ReactElement {
  return (
    <Label
      className={cn(
        "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
        "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
        "has-data-checked:border-primary has-data-checked:bg-primary/5 dark:has-data-checked:bg-primary/10",
        className
      )}
      data-slot="field-label"
      {...props}
    />
  );
}

export type FieldTitleProps = React.ComponentProps<"div">;

function FieldTitle({ className, ...props }: FieldTitleProps): ReactElement {
  return (
    <div
      className={cn(
        "flex w-fit items-center gap-2 text-label-medium leading-snug group-data-[disabled=true]/field:opacity-50",
        className
      )}
      data-slot="field-label"
      {...props}
    />
  );
}

export type FieldDescriptionProps = React.ComponentProps<"p">;

function FieldDescription({
  className,
  ...props
}: FieldDescriptionProps): ReactElement {
  return (
    <p
      className={cn(
        "text-caption leading-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance",
        "last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
        "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
        className
      )}
      data-slot="field-description"
      {...props}
    />
  );
}

export type FieldSeparatorProps = React.ComponentProps<"div"> & {
  children?: React.ReactNode;
};

function FieldSeparator({
  children,
  className,
  ...props
}: FieldSeparatorProps): ReactElement {
  return (
    <div
      className={cn(
        "relative -my-2 h-5 text-body-small group-data-[variant=outline]/field-group:-mb-2",
        className
      )}
      data-content={Boolean(children)}
      data-slot="field-separator"
      {...props}
    >
      <Separator className="absolute inset-0 top-1/2" />
      {children ? (
        <span
          className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
          data-slot="field-separator-content"
        >
          {children}
        </span>
      ) : null}
    </div>
  );
}

export type FieldErrorProps = React.ComponentProps<"div"> & {
  errors?: ({ message?: string } | undefined)[];
};

function FieldError({
  className,
  children,
  errors,
  ...props
}: FieldErrorProps): ReactElement | null {
  const content = useMemo(() => {
    if (children) {
      return children;
    }

    if (!errors?.length) {
      return null;
    }

    const uniqueErrors = Array.from(
      new Map(errors.map((error) => [error?.message, error])).values()
    );

    if (uniqueErrors.length === 1) {
      return uniqueErrors[0]?.message;
    }

    return (
      <ul className="ml-4 flex list-disc flex-col gap-1">
        {uniqueErrors.map(
          (error) =>
            error?.message && <li key={error.message}>{error.message}</li>
        )}
      </ul>
    );
  }, [children, errors]);

  if (!content) {
    return null;
  }

  return (
    <div
      className={cn("text-left text-caption text-destructive", className)}
      data-slot="field-error"
      role="alert"
      {...props}
    >
      {content}
    </div>
  );
}

export {
  Field,
  FieldLabel,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLegend,
  FieldSeparator,
  FieldSet,
  FieldContent,
  FieldTitle,
};
