'use client';

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { listSpecialties } from '@/lib/services/specialties';
import { listUsers, ManagedUser } from '@/lib/services/users';
import type { Dentist, Specialty } from '@/lib/types';

const UF = [
  'AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS',
  'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC',
  'SP', 'SE', 'TO',
];

const schema = z.object({
  fullName: z.string().min(3, 'Informe o nome completo'),
  cro: z.string().min(1, 'Informe o CRO').max(20),
  croState: z.string().length(2, 'Selecione a UF'),
  bio: z.string().max(2000).optional().or(z.literal('')),
  photo: z.custom<FileList | undefined>().optional(),
  isActive: z.boolean().default(true),
  userId: z.string().optional().default(''),
  specialtyIds: z.preprocess(
    (value) =>
      Array.isArray(value)
        ? value
            .map((item) => (typeof item === 'string' ? Number(item) : item))
            .filter(
              (item): item is number =>
                typeof item === 'number' && Number.isFinite(item),
            )
        : [],
    z.array(z.number()),
  ),
});

export type DentistFormValues = z.infer<typeof schema>;

export default function DentistForm({
  initial,
  canLinkUser,
  submitting,
  onSubmit,
  onCancel,
}: {
  initial?: Dentist;
  canLinkUser: boolean;
  submitting: boolean;
  onSubmit: (values: DentistFormValues) => void | Promise<void>;
  onCancel?: () => void;
}) {
  const [specialties, setSpecialties] = useState<Specialty[]>([]);
  const [users, setUsers] = useState<ManagedUser[]>([]);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<DentistFormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      fullName: initial?.fullName ?? '',
      cro: initial?.cro ?? '',
      croState: initial?.croState ?? '',
      bio: initial?.bio ?? '',
      photo: undefined,
      isActive: initial?.isActive ?? true,
      userId: initial?.userId ? String(initial.userId) : '',
      specialtyIds: initial?.specialties?.map((s) => s.id) ?? [],
    },
  });

  useEffect(() => {
    reset({
      fullName: initial?.fullName ?? '',
      cro: initial?.cro ?? '',
      croState: initial?.croState ?? '',
      bio: initial?.bio ?? '',
      photo: undefined,
      isActive: initial?.isActive ?? true,
      userId: initial?.userId ? String(initial.userId) : '',
      specialtyIds: initial?.specialties?.map((s) => s.id) ?? [],
    });
  }, [initial, reset]);

  useEffect(() => {
    listSpecialties()
      .then((r) => setSpecialties(r.data))
      .catch(() => setSpecialties([]));
  }, []);

  useEffect(() => {
    if (!canLinkUser) return;
    listUsers()
      .then((r) => setUsers(r.data))
      .catch(() => setUsers([]));
  }, [canLinkUser]);

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate className="card border-0 shadow-sm">
      <div className="card-body">
        <div className="row g-3">
          <div className="col-12 col-md-6">
            <label htmlFor="fullName" className="form-label">
              Nome completo *
            </label>
            <input
              id="fullName"
              className={`form-control ${errors.fullName ? 'is-invalid' : ''}`}
              {...register('fullName')}
            />
            {errors.fullName && (
              <div className="invalid-feedback">{errors.fullName.message}</div>
            )}
          </div>

          <div className="col-6 col-md-3">
            <label htmlFor="cro" className="form-label">
              CRO *
            </label>
            <input
              id="cro"
              className={`form-control ${errors.cro ? 'is-invalid' : ''}`}
              {...register('cro')}
            />
            {errors.cro && (
              <div className="invalid-feedback">{errors.cro.message}</div>
            )}
          </div>

          <div className="col-6 col-md-3">
            <label htmlFor="croState" className="form-label">
              UF do CRO *
            </label>
            <select
              id="croState"
              className={`form-select ${errors.croState ? 'is-invalid' : ''}`}
              {...register('croState')}
            >
              <option value="">UF</option>
              {UF.map((uf) => (
                <option key={uf} value={uf}>
                  {uf}
                </option>
              ))}
            </select>
            {errors.croState && (
              <div className="invalid-feedback">{errors.croState.message}</div>
            )}
          </div>

          <div className="col-12">
            <label htmlFor="bio" className="form-label">
              Mini-currículo
            </label>
            <textarea
              id="bio"
              rows={3}
              className={`form-control ${errors.bio ? 'is-invalid' : ''}`}
              {...register('bio')}
            />
            {errors.bio && (
              <div className="invalid-feedback">{errors.bio.message}</div>
            )}
          </div>

          <div className="col-12 col-md-8">
            <label htmlFor="photo" className="form-label">
              Foto
            </label>
            <input
              id="photo"
              type="file"
              accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
              className={`form-control ${errors.photo ? 'is-invalid' : ''}`}
              {...register('photo')}
            />
            {initial?.photoUrl && (
              <div className="form-text">
                Já existe uma foto cadastrada. Selecione outro arquivo para substituí-la.
              </div>
            )}
            <div className="form-text">JPG, PNG ou WEBP, até 5 MB.</div>
            {errors.photo && (
              <div className="invalid-feedback">{errors.photo.message}</div>
            )}
          </div>

          {canLinkUser && (
            <div className="col-12 col-md-4">
              <label htmlFor="userId" className="form-label">
                Vincular usuário
              </label>
              <select id="userId" className="form-select" {...register('userId')}>
                <option value="">Nenhum</option>
                {users.map((u) => (
                  <option key={u.id} value={u.id}>
                    {u.email} ({u.role})
                  </option>
                ))}
              </select>
            </div>
          )}

          <div className="col-12">
            <span className="form-label d-block">Especialidades</span>
            <div className="row g-2">
              {specialties.length === 0 && (
                <p className="text-muted mb-0">
                  Nenhuma especialidade cadastrada.
                </p>
              )}
              {specialties.map((s) => (
                <div className="col-6 col-md-4" key={s.id}>
                  <div className="form-check">
                    <input
                      type="checkbox"
                      className="form-check-input"
                      id={`spec-${s.id}`}
                      value={s.id}
                      {...register('specialtyIds', { valueAsNumber: true })}
                    />
                    <label className="form-check-label" htmlFor={`spec-${s.id}`}>
                      {s.name}
                    </label>
                  </div>
                </div>
              ))}
            </div>
            {errors.specialtyIds && (
              <div className="text-danger small mt-2">
                Não foi possível validar as especialidades selecionadas.
              </div>
            )}
          </div>

          <div className="col-12">
            <div className="form-check form-switch">
              <input
                type="checkbox"
                role="switch"
                className="form-check-input"
                id="isActive"
                {...register('isActive')}
              />
              <label className="form-check-label" htmlFor="isActive">
                Dentista ativo
              </label>
            </div>
          </div>
        </div>
      </div>
      <div className="card-footer bg-white d-flex justify-content-end gap-2">
        {onCancel && (
          <button
            type="button"
            className="btn btn-outline-secondary"
            onClick={onCancel}
            disabled={submitting}
          >
            Cancelar
          </button>
        )}
        <button type="submit" className="btn btn-primary" disabled={submitting}>
          {submitting && (
            <span
              className="spinner-border spinner-border-sm me-2"
              role="status"
              aria-hidden="true"
            />
          )}
          Salvar
        </button>
      </div>
    </form>
  );
}
