'use client';

import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import type { Gender, Patient } from '@/lib/types';
import { GENDER_LABELS } from '@/lib/types';

const schema = z.object({
  fullName: z.string().min(3, 'Informe o nome completo'),
  cpf: z
    .string()
    .optional()
    .or(z.literal(''))
    .refine(
      (v) => !v || v.replace(/\D/g, '').length === 11,
      'CPF deve conter 11 dígitos',
    ),
  birthDate: z.string().optional().or(z.literal('')),
  gender: z.string().optional().or(z.literal('')),
  email: z
    .string()
    .optional()
    .or(z.literal(''))
    .refine(
      (v) => !v || /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v),
      'E-mail inválido',
    ),
  phone: z.string().optional().or(z.literal('')),
  zipCode: z.string().optional().or(z.literal('')),
  street: z.string().optional().or(z.literal('')),
  number: z.string().optional().or(z.literal('')),
  complement: z.string().optional().or(z.literal('')),
  district: z.string().optional().or(z.literal('')),
  city: z.string().optional().or(z.literal('')),
  state: z.string().optional().or(z.literal('')),
  notes: z.string().max(2000).optional().or(z.literal('')),
  isActive: z.boolean(),
});

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

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',
];

function toDefaults(initial?: Patient): PatientFormValues {
  return {
    fullName: initial?.fullName ?? '',
    cpf: initial?.cpf ?? '',
    birthDate: initial?.birthDate ? initial.birthDate.slice(0, 10) : '',
    gender: initial?.gender ?? '',
    email: initial?.email ?? '',
    phone: initial?.phone ?? '',
    zipCode: initial?.zipCode ?? '',
    street: initial?.street ?? '',
    number: initial?.number ?? '',
    complement: initial?.complement ?? '',
    district: initial?.district ?? '',
    city: initial?.city ?? '',
    state: initial?.state ?? '',
    notes: initial?.notes ?? '',
    isActive: initial?.isActive ?? true,
  };
}

export default function PatientForm({
  initial,
  submitting,
  onSubmit,
  onCancel,
}: {
  initial?: Patient;
  submitting: boolean;
  onSubmit: (values: PatientFormValues) => void | Promise<void>;
  onCancel?: () => void;
}) {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<PatientFormValues>({
    resolver: zodResolver(schema),
    defaultValues: toDefaults(initial),
  });

  useEffect(() => {
    reset(toDefaults(initial));
  }, [initial, reset]);

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate className="card border-0 shadow-sm">
      <div className="card-body">
        <h2 className="h6 text-uppercase text-muted mb-3">Dados pessoais</h2>
        <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="cpf" className="form-label">
              CPF
            </label>
            <input
              id="cpf"
              className={`form-control ${errors.cpf ? 'is-invalid' : ''}`}
              placeholder="000.000.000-00"
              {...register('cpf')}
            />
            {errors.cpf && (
              <div className="invalid-feedback">{errors.cpf.message}</div>
            )}
          </div>
          <div className="col-6 col-md-3">
            <label htmlFor="birthDate" className="form-label">
              Nascimento
            </label>
            <input
              id="birthDate"
              type="date"
              className="form-control"
              {...register('birthDate')}
            />
          </div>
          <div className="col-6 col-md-3">
            <label htmlFor="gender" className="form-label">
              Gênero
            </label>
            <select id="gender" className="form-select" {...register('gender')}>
              <option value="">Não informado</option>
              {(Object.keys(GENDER_LABELS) as Gender[]).map((g) => (
                <option key={g} value={g}>
                  {GENDER_LABELS[g]}
                </option>
              ))}
            </select>
          </div>
          <div className="col-6 col-md-4">
            <label htmlFor="email" className="form-label">
              E-mail
            </label>
            <input
              id="email"
              type="email"
              className={`form-control ${errors.email ? 'is-invalid' : ''}`}
              {...register('email')}
            />
            {errors.email && (
              <div className="invalid-feedback">{errors.email.message}</div>
            )}
          </div>
          <div className="col-6 col-md-3">
            <label htmlFor="phone" className="form-label">
              Telefone
            </label>
            <input
              id="phone"
              className="form-control"
              placeholder="(11) 99999-9999"
              {...register('phone')}
            />
          </div>
        </div>

        <h2 className="h6 text-uppercase text-muted mb-3 mt-4">Endereço</h2>
        <div className="row g-3">
          <div className="col-4 col-md-2">
            <label htmlFor="zipCode" className="form-label">
              CEP
            </label>
            <input id="zipCode" className="form-control" {...register('zipCode')} />
          </div>
          <div className="col-8 col-md-6">
            <label htmlFor="street" className="form-label">
              Logradouro
            </label>
            <input id="street" className="form-control" {...register('street')} />
          </div>
          <div className="col-4 col-md-1">
            <label htmlFor="number" className="form-label">
              Nº
            </label>
            <input id="number" className="form-control" {...register('number')} />
          </div>
          <div className="col-8 col-md-3">
            <label htmlFor="complement" className="form-label">
              Complemento
            </label>
            <input
              id="complement"
              className="form-control"
              {...register('complement')}
            />
          </div>
          <div className="col-6 col-md-3">
            <label htmlFor="district" className="form-label">
              Bairro
            </label>
            <input id="district" className="form-control" {...register('district')} />
          </div>
          <div className="col-6 col-md-6">
            <label htmlFor="city" className="form-label">
              Cidade
            </label>
            <input id="city" className="form-control" {...register('city')} />
          </div>
          <div className="col-6 col-md-2">
            <label htmlFor="state" className="form-label">
              UF
            </label>
            <select id="state" className="form-select" {...register('state')}>
              <option value="">UF</option>
              {UF.map((uf) => (
                <option key={uf} value={uf}>
                  {uf}
                </option>
              ))}
            </select>
          </div>
        </div>

        <h2 className="h6 text-uppercase text-muted mb-3 mt-4">Observações</h2>
        <textarea
          rows={3}
          className="form-control"
          placeholder="Anotações administrativas (não use para dados clínicos)"
          {...register('notes')}
        />

        <div className="form-check form-switch mt-3">
          <input
            type="checkbox"
            role="switch"
            className="form-check-input"
            id="isActive"
            {...register('isActive')}
          />
          <label className="form-check-label" htmlFor="isActive">
            Paciente ativo
          </label>
        </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>
  );
}
