import React, { useState } from "react";
import { Dropdown, IconButton } from "@os-legal/ui";
import { Trash2 } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import styled from "styled-components";
import { OS_LEGAL_COLORS } from "../../assets/configurations/osLegalStyles";

export interface FieldType {
  fieldName: string;
  fieldType: string;
  id: string; // Added for stable animations
}

interface ModelFieldBuilderProps {
  onFieldsChange: (fields: FieldType[]) => void;
  initialFields?: FieldType[];
}

const containerVariants = {
  hidden: {
    opacity: 0,
    transition: { staggerChildren: 0.05, staggerDirection: -1 },
  },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.1,
      delayChildren: 0.2,
    },
  },
};

const fieldVariants = {
  hidden: {
    opacity: 0,
    x: -20,
    transition: { type: "tween" },
  },
  visible: {
    opacity: 1,
    x: 0,
    transition: { type: "spring", stiffness: 300, damping: 25 },
  },
  exit: {
    opacity: 0,
    x: -20,
    transition: { duration: 0.2 },
  },
};

const FieldRow = styled(motion.div)`
  margin-bottom: 1rem;
  background: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
`;

const AddFieldButton = styled(motion.button)`
  background: ${OS_LEGAL_COLORS.primaryBlue};
  color: white;
  border: none;
  border-radius: 20px;
  padding: 12px 24px;
  cursor: pointer;
  width: 100%;
  margin-top: 1rem;
`;

/**
 * Component for building custom model fields with animations.
 */
export const ModelFieldBuilder: React.FC<ModelFieldBuilderProps> = ({
  onFieldsChange,
  initialFields = [],
}) => {
  const [fields, setFields] = useState<FieldType[]>(
    initialFields.map((f) => ({ ...f, id: Math.random().toString() }))
  );

  const addField = () => {
    const newField = {
      fieldName: "",
      fieldType: "str",
      id: Math.random().toString(),
    };
    setFields([...fields, newField]);
  };

  const removeField = (index: number) => {
    const newFields = [...fields];
    newFields.splice(index, 1);
    setFields(newFields);
    onFieldsChange(newFields);
  };

  const updateField = (
    index: number,
    key: "fieldName" | "fieldType",
    value: string
  ) => {
    const newFields = [...fields];
    newFields[index][key] = value;
    setFields(newFields);
    onFieldsChange(newFields);
  };

  return (
    <motion.div
      variants={containerVariants}
      initial="hidden"
      animate="visible"
      exit="hidden"
    >
      <div>
        <AnimatePresence>
          {fields.map((field, index) => (
            <FieldRow key={field.id} variants={fieldVariants} layout>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "6fr 6fr 4fr",
                  gap: "1rem",
                  alignItems: "center",
                }}
              >
                <div>
                  <label
                    style={{
                      display: "block",
                      marginBottom: "0.5rem",
                      fontWeight: 500,
                    }}
                  >
                    Field Name
                  </label>
                  <input
                    type="text"
                    placeholder="Field Name"
                    value={field.fieldName}
                    onChange={(e) =>
                      updateField(index, "fieldName", e.target.value)
                    }
                    required
                    style={{
                      width: "100%",
                      padding: "0.5rem 0.75rem",
                      border: "1px solid rgba(34,36,38,.15)",
                      borderRadius: "4px",
                      fontSize: "1rem",
                    }}
                  />
                </div>
                <div>
                  <label
                    style={{
                      display: "block",
                      marginBottom: "0.5rem",
                      fontWeight: 500,
                    }}
                  >
                    Field Type
                  </label>
                  <Dropdown
                    placeholder="Field Type"
                    value={field.fieldType}
                    options={[
                      { value: "int", label: "Integer" },
                      { value: "float", label: "Float" },
                      { value: "str", label: "String" },
                      { value: "bool", label: "Boolean" },
                    ]}
                    onChange={(value) =>
                      updateField(index, "fieldType", value as string)
                    }
                    mode="select"
                    fluid
                    clearable={false}
                  />
                </div>
                <div style={{ textAlign: "center" }}>
                  <IconButton
                    aria-label="Delete field"
                    variant="danger"
                    onClick={() => removeField(index)}
                  >
                    <Trash2 size={16} />
                  </IconButton>
                </div>
              </div>
            </FieldRow>
          ))}
        </AnimatePresence>

        <AddFieldButton
          onClick={addField}
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
        >
          Add Field
        </AddFieldButton>
      </div>
    </motion.div>
  );
};
