'use client';

import { useState, useEffect } from 'react';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';
import { BED_POSITIONS, COACH_TYPE_LABELS, getTariffRef } from './constants';
import type { SeatClass, CoachType, Route } from './types';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  editingClass: SeatClass | null;
  allClasses: SeatClass[];
  coachTypes: CoachType[];
  routes?: Route[];
  preselectedRouteId?: string | null;
  allowRouteOverride?: boolean;
  onSubmitGlobal: (payload: any) => Promise<void>;
  onSubmitOverride: (routeId: string, payload: any) => Promise<void>;
  isPending: boolean;
}

export default function RateModal({
  isOpen, onClose, editingClass, allClasses, coachTypes, routes,
  preselectedRouteId, allowRouteOverride, onSubmitGlobal, onSubmitOverride, isPending,
}: Props) {
  const [nationalityType, setNationalityType] = useState('LOCAL');
  const [coachTypeId, setCoachTypeId] = useState('');
  const [bedPosition, setBedPosition] = useState('');
  const [routeId, setRouteId] = useState(preselectedRouteId ?? '');
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!isOpen) return;
    setNationalityType(editingClass?.nationalityType ?? 'LOCAL');
    setCoachTypeId(editingClass?.coachTypeId ?? '');
    setBedPosition(editingClass?.bedPosition ?? '');
    setRouteId(preselectedRouteId ?? '');
    setError(null);
  }, [isOpen]); // eslint-disable-line react-hooks/exhaustive-deps

  const selectedCoachType = coachTypes.find(c => c.id === coachTypeId) ?? (editingClass as any)?.coachType;
  const isBedCoach = selectedCoachType?.name?.toLowerCase().includes('bed') ||
    selectedCoachType?.code?.toLowerCase().includes('bed');

  const suggestName = () => {
    if (!selectedCoachType) return '';
    const label = COACH_TYPE_LABELS[selectedCoachType.code] ?? selectedCoachType.name;
    const pos = bedPosition ? ` ${bedPosition.charAt(0) + bedPosition.slice(1).toLowerCase()}` : '';
    const nat = nationalityType === 'LOCAL' ? 'Local' : 'Intl';
    return `${label}${pos} (${nat})`;
  };

  const suggestRate = () => {
    if (!selectedCoachType) return '';
    const ref = getTariffRef(nationalityType, selectedCoachType.code, bedPosition || null);
    return ref ? String(ref) : '';
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    const fd = new FormData(e.currentTarget);

    try {
      if (routeId && !editingClass) {
        const matched = allClasses.find(c =>
          c.coachTypeId === coachTypeId &&
          c.nationalityType === nationalityType &&
          (c.bedPosition ?? null) === (bedPosition || null),
        );
        if (!matched) {
          setError('No matching seat class found for the selected combination. Create the global rate first.');
          return;
        }
        await onSubmitOverride(routeId, {
          seatClassId: matched.id,
          passengerCategory: 'ADULT',
          baseFareMinor: Math.round(Number(fd.get('baseFareMinor')) * 100) || 0,
          surchargeMinor: Math.round(Number(fd.get('surchargeMinor') ?? '0') * 100) || 0,
          validFrom: new Date().toISOString(),
        });
      } else {
        await onSubmitGlobal({
          coachTypeId,
          name: fd.get('name') as string,
          nationalityType,
          bedPosition: bedPosition || null,
          basePrice: Math.round(Number(fd.get('baseFareMinor')) * 100) || 0,
          insuranceFeeMinor: Math.round(Number(fd.get('insuranceFeeMinor') ?? '0') * 100) || 0,
          isActive: fd.get('isActive') === 'true',
        });
      }
      onClose();
    } catch (err: any) {
      setError(err?.response?.data?.message ?? err?.message ?? 'Failed to save');
    }
  };

  const isOverrideMode = !!routeId && !editingClass;
  const title = editingClass ? 'Edit Tariff Rate' : isOverrideMode ? 'Add Route Override' : 'Add Tariff Rate';

  return (
    <Modal isOpen={isOpen} onClose={onClose} title={title} size="lg">
      <form key={editingClass?.id ?? `new-${preselectedRouteId}`} onSubmit={handleSubmit} className="space-y-4">
        {error && (
          <div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-800 dark:text-red-200">
            {error}
          </div>
        )}

        {!editingClass && allowRouteOverride && (
          <div>
            <label className="label">Route Override (optional)</label>
            <select className="input w-full" value={routeId} onChange={e => setRouteId(e.target.value)}>
              <option value="">Global rate (applies to all routes)</option>
              {(routes ?? []).map(r => (
                <option key={r.id} value={r.id}>{r.name}{r.code ? ` (${r.code})` : ''}</option>
              ))}
            </select>
            {isOverrideMode && (
              <p className="text-xs text-muted-foreground mt-1">
                Override applies only to this route. A matching global seat class must already exist.
              </p>
            )}
          </div>
        )}

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="label">Passenger Nationality *</label>
            <select className="input" value={nationalityType} onChange={e => setNationalityType(e.target.value)} required>
              <option value="LOCAL">Local (Ethiopian / Djiboutian)</option>
              <option value="INTERNATIONAL">International (Foreign nationals)</option>
            </select>
          </div>

          <div>
            <label className="label">Coach Type *</label>
            <select
              className="input"
              value={coachTypeId}
              onChange={e => { setCoachTypeId(e.target.value); setBedPosition(''); }}
              required
            >
              <option value="">Select coach type</option>
              {coachTypes.map(ct => (
                <option key={ct.id} value={ct.id}>{ct.code} — {ct.name}</option>
              ))}
            </select>
          </div>

          {isBedCoach && (
            <div>
              <label className="label">Bed Position *</label>
              <select className="input" value={bedPosition} onChange={e => setBedPosition(e.target.value)} required>
                <option value="">Select bed position</option>
                {BED_POSITIONS.map(pos => <option key={pos} value={pos}>{pos}</option>)}
              </select>
              <p className="text-xs text-muted-foreground mt-1">
                {selectedCoachType?.code === 'HBC' ? 'Economy Bed: Upper / Middle / Lower' : 'VIP Bed: Upper / Lower'}
              </p>
            </div>
          )}

          {!isOverrideMode && (
            <div>
              <label className="label">Class Name *</label>
              <input
                type="text"
                name="name"
                className="input"
                defaultValue={editingClass?.name ?? ''}
                key={editingClass?.id ?? `name-${coachTypeId}-${bedPosition}-${nationalityType}`}
                placeholder={suggestName() || 'e.g. Economy Bed Upper (Local)'}
                required
              />
              {!editingClass && suggestName() && (
                <p className="text-xs text-muted-foreground mt-1">
                  Suggested:{' '}
                  <button type="button" className="text-primary underline" onClick={e => {
                    const inp = (e.currentTarget.closest('form')?.querySelector('input[name=name]') as HTMLInputElement);
                    if (inp) inp.value = suggestName();
                  }}>{suggestName()}</button>
                </p>
              )}
            </div>
          )}

          <div>
            <label className="label">Rate per km *</label>
            <input
              type="number"
              name="baseFareMinor"
              className="input"
              defaultValue={editingClass ? editingClass.baseFareMinor! / 100 : ''}
              key={editingClass?.id ?? `rate-${coachTypeId}-${bedPosition}-${nationalityType}`}
              placeholder={suggestRate() || 'e.g. 0.06'}
              min="0"
              step="any"
              required
            />
            {suggestRate() && (
              <p className="text-xs text-muted-foreground mt-1">
                Official tariff:{' '}
                <button type="button" className="text-primary underline" onClick={e => {
                  const inp = (e.currentTarget.closest('form')?.querySelector('input[name=baseFareMinor]') as HTMLInputElement);
                  if (inp) inp.value = suggestRate();
                }}>{suggestRate()}</button>
                {' '}(stored as {Math.round(Number(suggestRate()) * 100)})
              </p>
            )}
          </div>

          {/* Insurance fee — different field name depending on mode */}
          <div>
            <label className="label">Insurance Fee (ETB)</label>
            <input
              type="number"
              name={isOverrideMode ? 'surchargeMinor' : 'insuranceFeeMinor'}
              className="input"
              defaultValue={editingClass ? (editingClass.insuranceFeeMinor! / 100).toFixed(2) : '0.00'}
              key={editingClass?.id ?? `ins-${isOverrideMode}`}
              min="0"
              step="0.01"
              placeholder="e.g. 25.00"
            />
          </div>

          {!isOverrideMode && (
            <div>
              <label className="label">Status</label>
              <select name="isActive" className="input" defaultValue={editingClass?.isActive !== false ? 'true' : 'false'}>
                <option value="true">Active</option>
                <option value="false">Inactive</option>
              </select>
            </div>
          )}
        </div>

        <div className="flex justify-end gap-2 pt-4">
          <ActionButton type="button" variant="secondary" onClick={onClose}>Cancel</ActionButton>
          <ActionButton type="submit" loading={isPending}>
            {editingClass ? 'Update Rate' : isOverrideMode ? 'Create Override' : 'Create Rate'}
          </ActionButton>
        </div>
      </form>
    </Modal>
  );
}
