import { useEffect } from 'react';
import { Form as RemixForm } from "@remix-run/react";
import { Input } from "~/components/ui/Input";
import { Textarea } from "~/components/ui/Textarea";
import { Button } from "~/components/ui/Button";
import { FormField } from "~/components/ui/FormField";
import { Form, FormActions, FormSection, FormGrid } from "~/components/ui/Form";
import { useFormValidation } from "~/hooks/useFormValidation";
import { customerSchema } from "~/lib/form-validation";
import type { Customer } from "~/types/database";

interface EnhancedCustomerFormProps {
  customer?: Customer;
  onCancel: () => void;
  errors?: Record<string, string>;
  isLoading: boolean;
  onSubmit?: (data: any) => void;
}

export function EnhancedCustomerForm({
  customer,
  onCancel,
  errors = {},
  isLoading,
  onSubmit,
}: EnhancedCustomerFormProps) {
  const {
    values,
    errors: validationErrors,
    touched,
    isValid,
    setValue,
    setTouched,
    reset,
    validate,
    getFieldProps,
  } = useFormValidation({
    schema: customerSchema,
    initialValues: {
      name: customer?.name || "",
      phone: customer?.phone || "",
      email: customer?.email || "",
      address: customer?.address || "",
    },
    validateOnChange: true,
    validateOnBlur: true,
  });

  // Reset form when customer changes
  useEffect(() => {
    if (customer) {
      reset({
        name: customer.name || "",
        phone: customer.phone || "",
        email: customer.email || "",
        address: customer.address || "",
      });
    } else {
      reset({
        name: "",
        phone: "",
        email: "",
        address: "",
      });
    }
  }, [customer, reset]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const { isValid: formIsValid } = validate();
    
    if (formIsValid && onSubmit) {
      onSubmit(values);
    }
  };

  const isEditing = !!customer;
  const combinedErrors = { ...validationErrors, ...errors };

  return (
    <Form
      title={isEditing ? "تعديل بيانات العميل" : "إضافة عميل جديد"}
      description={isEditing ? "قم بتعديل بيانات العميل أدناه" : "أدخل بيانات العميل الجديد"}
      loading={isLoading}
      onSubmit={handleSubmit}
    >
      <input 
        type="hidden" 
        name="_action" 
        value={isEditing ? "update" : "create"} 
      />
      {isEditing && (
        <input type="hidden" name="id" value={customer.id} />
      )}

      <FormSection
        title="المعلومات الأساسية"
        description="البيانات الأساسية للعميل"
      >
        <FormGrid columns={2}>
          {/* Customer Name */}
          <FormField
            label="اسم العميل"
            required
            error={combinedErrors.name}
            htmlFor="name"
          >
            <Input
              id="name"
              name="name"
              type="text"
              placeholder="أدخل اسم العميل"
              disabled={isLoading}
              {...getFieldProps('name')}
            />
          </FormField>

          {/* Phone Number */}
          <FormField
            label="رقم الهاتف"
            error={combinedErrors.phone}
            htmlFor="phone"
            helperText="رقم الهاتف اختياري"
          >
            <Input
              id="phone"
              name="phone"
              type="tel"
              placeholder="أدخل رقم الهاتف"
              disabled={isLoading}
              dir="ltr"
              {...getFieldProps('phone')}
            />
          </FormField>
        </FormGrid>
      </FormSection>

      <FormSection
        title="معلومات الاتصال"
        description="بيانات الاتصال الإضافية"
      >
        {/* Email */}
        <FormField
          label="البريد الإلكتروني"
          error={combinedErrors.email}
          htmlFor="email"
          helperText="البريد الإلكتروني اختياري"
        >
          <Input
            id="email"
            name="email"
            type="email"
            placeholder="أدخل البريد الإلكتروني"
            disabled={isLoading}
            dir="ltr"
            {...getFieldProps('email')}
          />
        </FormField>

        {/* Address */}
        <FormField
          label="العنوان"
          error={combinedErrors.address}
          htmlFor="address"
          helperText="عنوان العميل اختياري"
        >
          <Textarea
            id="address"
            name="address"
            placeholder="أدخل عنوان العميل"
            rows={3}
            disabled={isLoading}
            {...getFieldProps('address')}
          />
        </FormField>
      </FormSection>

      <FormActions>
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={isLoading}
        >
          إلغاء
        </Button>
        
        <Button
          type="submit"
          disabled={isLoading || !isValid || !values.name?.trim()}
          loading={isLoading}
        >
          {isEditing ? "تحديث العميل" : "إنشاء العميل"}
        </Button>
      </FormActions>
    </Form>
  );
}