import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@components/atoms/Button';
import { FormField } from '@components/molecules/FormField';
import { Select } from '@components/organisms/Select';
import { useCompanies } from '../hooks';
import type { Company, CreateCompanyDto, UpdateCompanyDto } from '../types';

const createCompanySchema = z.object({
  name: z.string().min(2, 'Mínimo 2 caracteres'),
  legalName: z.string().optional(),
  taxId: z.string().optional(),
  parentCompanyId: z.string().optional(),
  settings: z.object({
    email: z.string().email('Email inválido').optional().or(z.literal('')),
    phone: z.string().optional(),
    website: z.string().optional(),
    taxRegime: z.string().optional(),
    fiscalPosition: z.string().optional(),
    address: z.string().optional(),
    city: z.string().optional(),
    state: z.string().optional(),
    country: z.string().optional(),
    zipCode: z.string().optional(),
  }).optional(),
});

const updateCompanySchema = createCompanySchema;

type CreateFormData = z.infer<typeof createCompanySchema>;
type UpdateFormData = z.infer<typeof updateCompanySchema>;

interface CompanyFormProps {
  company?: Company;
  onSubmit: (data: CreateCompanyDto | UpdateCompanyDto) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
}

export function CompanyForm({ company, onSubmit, onCancel, isLoading }: CompanyFormProps) {
  const isEditing = !!company;
  const { companies } = useCompanies({ limit: 100 });

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<CreateFormData | UpdateFormData>({
    resolver: zodResolver(isEditing ? updateCompanySchema : createCompanySchema),
    defaultValues: company
      ? {
          name: company.name,
          legalName: company.legalName || '',
          taxId: company.taxId || '',
          parentCompanyId: company.parentCompanyId || '',
          settings: {
            email: company.settings?.email || '',
            phone: company.settings?.phone || '',
            website: company.settings?.website || '',
            taxRegime: company.settings?.taxRegime || '',
            fiscalPosition: company.settings?.fiscalPosition || '',
            address: company.settings?.address || '',
            city: company.settings?.city || '',
            state: company.settings?.state || '',
            country: company.settings?.country || '',
            zipCode: company.settings?.zipCode || '',
          },
        }
      : {
          name: '',
          legalName: '',
          taxId: '',
          parentCompanyId: '',
          settings: {
            email: '',
            phone: '',
            website: '',
            taxRegime: '',
            fiscalPosition: '',
            address: '',
            city: '',
            state: '',
            country: '',
            zipCode: '',
          },
        },
  });

  const selectedParentId = watch('parentCompanyId');

  // Filter out current company from parent options (can't be its own parent)
  const parentOptions = [
    { value: '', label: 'Sin empresa matriz' },
    ...companies
      .filter((c) => c.id !== company?.id)
      .map((c) => ({ value: c.id, label: c.name })),
  ];

  const handleFormSubmit = async (data: CreateFormData | UpdateFormData) => {
    // Clean up empty optional fields
    const cleanData: CreateCompanyDto | UpdateCompanyDto = {
      name: data.name,
      ...(data.legalName && { legalName: data.legalName }),
      ...(data.taxId && { taxId: data.taxId }),
      ...(data.parentCompanyId && { parentCompanyId: data.parentCompanyId }),
      settings: {
        ...(data.settings?.email && { email: data.settings.email }),
        ...(data.settings?.phone && { phone: data.settings.phone }),
        ...(data.settings?.website && { website: data.settings.website }),
        ...(data.settings?.taxRegime && { taxRegime: data.settings.taxRegime }),
        ...(data.settings?.fiscalPosition && { fiscalPosition: data.settings.fiscalPosition }),
        ...(data.settings?.address && { address: data.settings.address }),
        ...(data.settings?.city && { city: data.settings.city }),
        ...(data.settings?.state && { state: data.settings.state }),
        ...(data.settings?.country && { country: data.settings.country }),
        ...(data.settings?.zipCode && { zipCode: data.settings.zipCode }),
      },
    };
    await onSubmit(cleanData);
  };

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
      {/* Basic Info */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900">Información básica</h3>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <FormField
            label="Nombre comercial"
            error={errors.name?.message}
            required
          >
            <input
              {...register('name')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="Mi Empresa S.A."
            />
          </FormField>

          <FormField
            label="Razón social"
            error={errors.legalName?.message}
          >
            <input
              {...register('legalName')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="Mi Empresa Sociedad Anónima de Capital Variable"
            />
          </FormField>
        </div>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <FormField
            label="RFC / Tax ID"
            error={errors.taxId?.message}
          >
            <input
              {...register('taxId')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="ABC123456XYZ"
            />
          </FormField>

          <FormField
            label="Empresa matriz"
            error={errors.parentCompanyId?.message}
          >
            <Select
              options={parentOptions}
              value={selectedParentId || ''}
              onChange={(value) => setValue('parentCompanyId', value as string)}
              placeholder="Seleccionar..."
            />
          </FormField>
        </div>
      </div>

      {/* Contact Info */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900">Información de contacto</h3>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <FormField
            label="Email"
            error={errors.settings?.email?.message}
          >
            <input
              {...register('settings.email')}
              type="email"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="contacto@miempresa.com"
            />
          </FormField>

          <FormField
            label="Teléfono"
            error={errors.settings?.phone?.message}
          >
            <input
              {...register('settings.phone')}
              type="tel"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="+52 55 1234 5678"
            />
          </FormField>
        </div>

        <FormField
          label="Sitio web"
          error={errors.settings?.website?.message}
        >
          <input
            {...register('settings.website')}
            type="url"
            className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
            placeholder="https://www.miempresa.com"
          />
        </FormField>
      </div>

      {/* Fiscal Info */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900">Información fiscal</h3>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <FormField
            label="Régimen fiscal"
            error={errors.settings?.taxRegime?.message}
          >
            <input
              {...register('settings.taxRegime')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="601 - General de Ley"
            />
          </FormField>

          <FormField
            label="Posición fiscal"
            error={errors.settings?.fiscalPosition?.message}
          >
            <input
              {...register('settings.fiscalPosition')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="General"
            />
          </FormField>
        </div>
      </div>

      {/* Address */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900">Dirección</h3>

        <FormField
          label="Dirección"
          error={errors.settings?.address?.message}
        >
          <input
            {...register('settings.address')}
            type="text"
            className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
            placeholder="Av. Principal #123, Col. Centro"
          />
        </FormField>

        <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
          <FormField label="Ciudad" error={errors.settings?.city?.message}>
            <input
              {...register('settings.city')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="Ciudad de México"
            />
          </FormField>

          <FormField label="Estado" error={errors.settings?.state?.message}>
            <input
              {...register('settings.state')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="CDMX"
            />
          </FormField>

          <FormField label="País" error={errors.settings?.country?.message}>
            <input
              {...register('settings.country')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="México"
            />
          </FormField>

          <FormField label="C.P." error={errors.settings?.zipCode?.message}>
            <input
              {...register('settings.zipCode')}
              type="text"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="06600"
            />
          </FormField>
        </div>
      </div>

      <div className="flex justify-end gap-3 pt-4 border-t">
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancelar
        </Button>
        <Button type="submit" isLoading={isLoading}>
          {isEditing ? 'Guardar cambios' : 'Crear empresa'}
        </Button>
      </div>
    </form>
  );
}
