import { Button } from '@/components/ui/button';
import { Field, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { apiClient } from '@/lib/api-client';
import type { Complex, UpdateComplexInput } from '@repo/api-contract';
import { updateComplexSchema } from '@repo/api-contract';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Building2, Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';

type ComplexDetailsSectionProps = {
  complex: Complex | null;
  isLoading: boolean;
  isError: boolean;
};

type FormValues = {
  complexName: string;
  physicalAddress: string;
  city: string;
  state: string;
  country: string;
};

export function ComplexDetailsSection({ complex, isLoading, isError }: ComplexDetailsSectionProps) {
  const queryClient = useQueryClient();
  const [formValues, setFormValues] = useState<FormValues>({
    complexName: '',
    physicalAddress: '',
    city: '',
    state: '',
    country: '',
  });
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  useEffect(() => {
    if (complex) {
      setFormValues({
        complexName: complex.complexName,
        physicalAddress: complex.physicalAddress ?? '',
        city: complex.city ?? '',
        state: complex.state ?? '',
        country: complex.country ?? '',
      });
    }
  }, [complex]);

  const updateMutation = useMutation({
    mutationFn: (data: UpdateComplexInput) => apiClient.complexes.update(complex!.id, data),
    onSuccess: (updatedComplex) => {
      setSuccessMessage('Datos actualizados correctamente.');
      setErrorMessage(null);
      queryClient.setQueryData(['complex-by-slug', complex?.complexSlug], updatedComplex);
    },
    onError: (error: Error) => {
      setErrorMessage(error.message || 'Error al actualizar los datos.');
      setSuccessMessage(null);
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);
    setSuccessMessage(null);

    const result = updateComplexSchema.safeParse({
      complexName: formValues.complexName,
      physicalAddress: formValues.physicalAddress || null,
      city: formValues.city || null,
      state: formValues.state || null,
      country: formValues.country || null,
    });

    if (!result.success) {
      setErrorMessage(result.error.issues[0]?.message || 'Datos inválidos.');
      return;
    }

    updateMutation.mutate(result.data);
  };

  if (isLoading) {
    return (
      <section className="rounded-xl border bg-card p-5">
        <div className="flex items-center gap-2">
          <Building2 className="size-5 text-muted-foreground" />
          <h3 className="text-lg font-medium">Datos del complejo</h3>
        </div>
        <Separator className="my-4" />
        <p className="text-sm text-muted-foreground">Cargando...</p>
      </section>
    );
  }

  if (isError || !complex) {
    return (
      <section className="rounded-xl border bg-card p-5">
        <div className="flex items-center gap-2">
          <Building2 className="size-5 text-muted-foreground" />
          <h3 className="text-lg font-medium">Datos del complejo</h3>
        </div>
        <Separator className="my-4" />
        <p className="text-sm text-destructive">No se pudieron cargar los datos del complejo.</p>
      </section>
    );
  }

  return (
    <section className="rounded-xl border bg-card p-5">
      <div className="flex items-center gap-2">
        <Building2 className="size-5 text-muted-foreground" />
        <h3 className="text-lg font-medium">Datos del complejo</h3>
      </div>
      <Separator className="my-4" />

      <form className="space-y-4" onSubmit={handleSubmit}>
        <Field>
          <FieldLabel htmlFor="complex-name">Nombre del complejo</FieldLabel>
          <Input
            id="complex-name"
            type="text"
            value={formValues.complexName}
            onChange={(e) => setFormValues((prev) => ({ ...prev, complexName: e.target.value }))}
          />
        </Field>

        <Field>
          <FieldLabel htmlFor="physical-address">Dirección</FieldLabel>
          <Input
            id="physical-address"
            type="text"
            placeholder="Ej: Av. San Martín 1234"
            value={formValues.physicalAddress}
            onChange={(e) =>
              setFormValues((prev) => ({ ...prev, physicalAddress: e.target.value }))
            }
          />
        </Field>

        <div className="grid gap-4 sm:grid-cols-3">
          <Field>
            <FieldLabel htmlFor="city">Ciudad</FieldLabel>
            <Input
              id="city"
              type="text"
              placeholder="Ej: Salta"
              value={formValues.city}
              onChange={(e) => setFormValues((prev) => ({ ...prev, city: e.target.value }))}
            />
          </Field>

          <Field>
            <FieldLabel htmlFor="state">Provincia / Estado</FieldLabel>
            <Input
              id="state"
              type="text"
              placeholder="Ej: Salta"
              value={formValues.state}
              onChange={(e) => setFormValues((prev) => ({ ...prev, state: e.target.value }))}
            />
          </Field>

          <Field>
            <FieldLabel htmlFor="country">País</FieldLabel>
            <Input
              id="country"
              type="text"
              placeholder="Ej: Argentina"
              value={formValues.country}
              onChange={(e) => setFormValues((prev) => ({ ...prev, country: e.target.value }))}
            />
          </Field>
        </div>

        {errorMessage && <p className="text-sm text-destructive">{errorMessage}</p>}
        {successMessage && (
          <p className="text-sm text-green-600 dark:text-green-400">{successMessage}</p>
        )}

        <div className="flex justify-end">
          <Button type="submit" disabled={updateMutation.isPending}>
            {updateMutation.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}
            Guardar cambios
          </Button>
        </div>
      </form>
    </section>
  );
}
