"use client";

import { useState } from "react";
import {
  useWatch,
  Controller,
  type Control,
  type UseFormRegister,
  type UseFormSetValue,
  type FieldErrors,
} from "react-hook-form";
import { Plus, Trash2, X, Calendar as CalendarIcon, MapPin } from "lucide-react";
import { calculateAge } from "@/lib/formatters/date";
import type { BookingFormValues } from "@/lib/validators/schemas";
import type { MeetingPoint } from "@/types/trip";
import styles from "./BookingForm.module.css";

interface ParticipantFieldsProps {
  index: number;
  control: Control<BookingFormValues>;
  register: UseFormRegister<BookingFormValues>;
  setValue: UseFormSetValue<BookingFormValues>;
  errors: FieldErrors<BookingFormValues>;
  canRemove: boolean;
  onRemove: () => void;
  meetingPoints: MeetingPoint[];
}

export default function ParticipantFields({
  index,
  control,
  register,
  setValue,
  errors,
  canRemove,
  onRemove,
  meetingPoints,
}: ParticipantFieldsProps) {
  const birthDate = useWatch({ control, name: `participants.${index}.birth_date` });
  const age = birthDate ? calculateAge(birthDate) : null;

  const watchedMeetingPointId = useWatch({ control, name: `participants.${index}.meeting_point_id` });
  const selectedMeetingPoint = meetingPoints.find((mp) => mp.id === watchedMeetingPointId);

  const medicalHistory =
    useWatch({ control, name: `participants.${index}.medical_history` }) ?? [];
  const [newIllness, setNewIllness] = useState("");

  const addIllness = () => {
    const trimmed = newIllness.trim();
    if (!trimmed) return;
    setValue(
      `participants.${index}.medical_history`,
      [...medicalHistory, trimmed],
      { shouldValidate: true }
    );
    setNewIllness("");
  };

  const removeIllness = (i: number) => {
    setValue(
      `participants.${index}.medical_history`,
      medicalHistory.filter((_, idx) => idx !== i),
      { shouldValidate: true }
    );
  };

  const participantErrors = errors.participants?.[index];

  return (
    <div className={styles.participantCard}>
      {/* Participant Header with Green Badge */}
      <div className={styles.participantHeader}>
        <div className={styles.participantBadge}>
          <span>PESERTA {index + 1}</span>
        </div>
        {canRemove && (
          <button
            type="button"
            onClick={onRemove}
            className={styles.removeParticipantBtn}
            id={`remove-participant-${index}`}
            aria-label={`Hapus peserta ${index + 1}`}
          >
            <Trash2 size={14} aria-hidden="true" />
            <span>Hapus</span>
          </button>
        )}
      </div>

      {/* Grid Fields */}
      <div className={styles.participantGrid}>
        {/* Nama Lengkap */}
        <div className={styles.formGroup}>
          <label htmlFor={`participant-${index}-name`} className={styles.formLabel}>
            Nama Lengkap <span className={styles.requiredStar}>*</span>
          </label>
          <input
            id={`participant-${index}-name`}
            type="text"
            placeholder="Sesuai KTP"
            className={`${styles.formInput} ${participantErrors?.name ? styles.inputError : ""}`}
            {...register(`participants.${index}.name`)}
          />
          {participantErrors?.name && (
            <span className={styles.errorText}>{participantErrors.name.message}</span>
          )}
        </div>

        {/* Meeting Point — dipilih per-peserta */}
        <div className={styles.formGroup}>
          <label htmlFor={`participant-${index}-meeting-point`} className={styles.formLabel}>
            Meeting Point <span className={styles.requiredStar}>*</span>
          </label>
          <Controller
            name={`participants.${index}.meeting_point_id`}
            control={control}
            render={({ field }) => (
              <div className={styles.selectWrapper}>
                <select
                  id={`participant-${index}-meeting-point`}
                  value={field.value ?? meetingPoints[0]?.id ?? ""}
                  onChange={(e) => field.onChange(e.target.value || null)}
                  className={styles.formSelect}
                >
                  {meetingPoints.map((mp) => (
                    <option key={mp.id} value={mp.id}>
                      {mp.name}
                    </option>
                  ))}
                </select>
              </div>
            )}
          />
          {selectedMeetingPoint?.map_url && (
            <a
              href={selectedMeetingPoint.map_url}
              target="_blank"
              rel="noopener noreferrer"
              className={styles.mapLinkBtn}
            >
              <MapPin size={14} aria-hidden />
              <span>Buka di Google Maps</span>
            </a>
          )}
        </div>

        {/* Tanggal Lahir with Age Hint */}
        <div className={styles.formGroup}>
          <div className={styles.labelWithHintRow}>
            <label htmlFor={`participant-${index}-birth-date`} className={styles.formLabel}>
              Tanggal Lahir <span className={styles.requiredStar}>*</span>
            </label>
            {age !== null && (
              <span className={styles.ageBadge}>Usia: {age} tahun</span>
            )}
          </div>
          <div className={styles.dateInputWrapper}>
            <input
              id={`participant-${index}-birth-date`}
              type="date"
              className={`${styles.formInput} ${participantErrors?.birth_date ? styles.inputError : ""}`}
              {...register(`participants.${index}.birth_date`)}
            />
          </div>
          {participantErrors?.birth_date && (
            <span className={styles.errorText}>{participantErrors.birth_date.message}</span>
          )}
        </div>

        {/* Berat Badan */}
        <div className={styles.formGroup}>
          <label htmlFor={`participant-${index}-weight`} className={styles.formLabel}>
            Berat Badan (KG) <span className={styles.requiredStar}>*</span>
          </label>
          <input
            id={`participant-${index}-weight`}
            type="number"
            placeholder="0"
            min={1}
            max={300}
            className={`${styles.formInput} ${participantErrors?.weight_kg ? styles.inputError : ""}`}
            {...register(`participants.${index}.weight_kg`, { valueAsNumber: true })}
          />
          {participantErrors?.weight_kg && (
            <span className={styles.errorText}>{participantErrors.weight_kg.message}</span>
          )}
        </div>

        {/* Tinggi Badan */}
        <div className={styles.formGroup}>
          <label htmlFor={`participant-${index}-height`} className={styles.formLabel}>
            Tinggi Badan (CM) <span className={styles.requiredStar}>*</span>
          </label>
          <input
            id={`participant-${index}-height`}
            type="number"
            placeholder="0"
            min={1}
            max={300}
            className={`${styles.formInput} ${participantErrors?.height_cm ? styles.inputError : ""}`}
            {...register(`participants.${index}.height_cm`, { valueAsNumber: true })}
          />
          {participantErrors?.height_cm && (
            <span className={styles.errorText}>{participantErrors.height_cm.message}</span>
          )}
        </div>

        {/* Jenis Kelamin */}
        <div className={styles.formGroup}>
          <label htmlFor={`participant-${index}-gender`} className={styles.formLabel}>
            Jenis Kelamin <span className={styles.requiredStar}>*</span>
          </label>
          <div className={styles.selectWrapper}>
            <select
              id={`participant-${index}-gender`}
              className={`${styles.formSelect} ${participantErrors?.gender ? styles.inputError : ""}`}
              {...register(`participants.${index}.gender`)}
            >
              <option value="MALE">Laki-laki</option>
              <option value="FEMALE">Perempuan</option>
            </select>
          </div>
          {participantErrors?.gender && (
            <span className={styles.errorText}>{participantErrors.gender.message}</span>
          )}
        </div>

        {/* No. WhatsApp Aktif */}
        <div className={styles.formGroup}>
          <label htmlFor={`participant-${index}-whatsapp`} className={styles.formLabel}>
            No. WhatsApp Aktif <span className={styles.requiredStar}>*</span>
          </label>
          <div className={styles.phoneInputGroup}>
            <span className={styles.phonePrefix}>+62</span>
            <input
              id={`participant-${index}-whatsapp`}
              type="tel"
              placeholder="8123456789"
              className={`${styles.phoneInput} ${participantErrors?.whatsapp ? styles.inputError : ""}`}
              {...register(`participants.${index}.whatsapp`)}
            />
          </div>
          {participantErrors?.whatsapp && (
            <span className={styles.errorText}>{participantErrors.whatsapp.message}</span>
          )}
        </div>

        {/* No. Darurat (WhatsApp Aktif) */}
        <div className={`${styles.formGroup} ${styles.fullWidthOnMobile}`}>
          <label htmlFor={`participant-${index}-emergency-whatsapp`} className={styles.formLabel}>
            No. Darurat (WhatsApp Aktif) <span className={styles.requiredStar}>*</span>
          </label>
          <div className={styles.phoneInputGroup}>
            <span className={styles.phonePrefix}>+62</span>
            <input
              id={`participant-${index}-emergency-whatsapp`}
              type="tel"
              placeholder="8123456789"
              className={`${styles.phoneInput} ${participantErrors?.emergency_whatsapp ? styles.inputError : ""}`}
              {...register(`participants.${index}.emergency_whatsapp`)}
            />
          </div>
          <span className={styles.fieldHint}>
            Kontak keluarga/teman yang bisa dihubungi saat darurat
          </span>
          {participantErrors?.emergency_whatsapp && (
            <span className={styles.errorText}>{participantErrors.emergency_whatsapp.message}</span>
          )}
        </div>
      </div>

      {/* Riwayat Penyakit Berat Section */}
      <div className={styles.medicalSection}>
        <div className={styles.medicalHeader}>
          <label htmlFor={`participant-${index}-medical-input`} className={styles.formLabel}>
            Riwayat Penyakit Berat
          </label>
          <span className={styles.medicalHint}>Kosongkan jika tidak ada.</span>
        </div>

        {/* Existing Illness Tags */}
        {medicalHistory.length > 0 && (
          <div className={styles.medicalTagsList}>
            {medicalHistory.map((illness, i) => (
              <span key={`${illness}-${i}`} className={styles.medicalTag}>
                <span>{illness}</span>
                <button
                  type="button"
                  onClick={() => removeIllness(i)}
                  className={styles.medicalTagRemoveBtn}
                  aria-label={`Hapus ${illness}`}
                >
                  <X size={12} aria-hidden="true" />
                </button>
              </span>
            ))}
          </div>
        )}

        {/* Add Illness Input Row */}
        <div className={styles.medicalInputRow}>
          <input
            id={`participant-${index}-medical-input`}
            type="text"
            value={newIllness}
            onChange={(e) => setNewIllness(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                addIllness();
              }
            }}
            placeholder="cth. Asma, Diabetes, dll."
            className={styles.formInput}
          />
          <button
            type="button"
            onClick={addIllness}
            className={styles.medicalAddBtn}
            id={`add-illness-${index}`}
          >
            <Plus size={15} aria-hidden="true" />
            <span>Tambah</span>
          </button>
        </div>
      </div>
    </div>
  );
}
