import React, { useState, useEffect } from 'react';
import { SchemaField, FieldSchema } from './SchemaField';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';

export type FormSchema = Record<string, FieldSchema>;

interface SchemaFormProps {
  schema: FormSchema;
  initialValues?: Record<string, any>;
  onSubmit: (values: Record<string, any>) => void | Promise<void>;
  isSubmitting?: boolean;
  submitLabel?: string;
  errors?: Record<string, string>;
}

export function SchemaForm({
  schema,
  initialValues = {},
  onSubmit,
  isSubmitting = false,
  submitLabel = 'Save Settings',
  errors = {},
}: SchemaFormProps) {
  const [values, setValues] = useState<Record<string, any>>(initialValues);

  useEffect(() => {
    setValues(initialValues);
  }, [initialValues]);

  const handleChange = (name: string, value: any) => {
    setValues((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await onSubmit(values);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {Object.entries(schema).map(([name, fieldSchema]) => (
        <SchemaField
          key={name}
          name={name}
          schema={fieldSchema}
          value={values[name]}
          onChange={(value) => handleChange(name, value)}
          error={errors[name]}
        />
      ))}

      <div className="flex justify-end pt-4 border-t">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
          {submitLabel}
        </Button>
      </div>
    </form>
  );
}
