/**
 * ResourceBooking — pick a resource and book it for the selected appointment.
 *
 * The backend's book-resource endpoint returns 409 on time overlap, which we
 * surface as a conflict warning. Resource list is loaded lazily by the parent
 * (we accept it as a prop to keep this component simple).
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/Button';
import { Select } from '@/components/ui/Select';
import {
  bookResource,
  type CalendarEntry,
  type Resource,
  type ResourceBooking,
} from '@/api/calendar';

export interface ResourceBookingProps {
  entry: CalendarEntry;
  resources: Resource[];
  onBooked?: (booking: ResourceBooking) => void;
}

export function ResourceBooking({ entry, resources, onBooked }: ResourceBookingProps) {
  const { t } = useTranslation();
  const [resourceId, setResourceId] = useState<string>('');
  const [busy, setBusy] = useState(false);
  const [conflict, setConflict] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const handleBook = async () => {
    setError(null);
    setConflict(null);
    setSuccess(null);
    if (!resourceId) {
      setError(t('calendar.resources.select'));
      return;
    }
    if (!entry.start_at || !entry.end_at) {
      setError(t('calendar.resources.missingTimes'));
      return;
    }
    setBusy(true);
    try {
      const booking = await bookResource(entry.id, { resource_id: resourceId });
      setSuccess(t('calendar.resources.booked'));
      onBooked?.(booking);
    } catch (e) {
      const err = e as { status?: number; message?: string };
      if (err.status === 409) {
        setConflict(t('calendar.resources.conflict'));
      } else {
        setError(err.message ?? t('calendar.errorSave'));
      }
    } finally {
      setBusy(false);
    }
  };

  const options = [
    { value: '', label: t('calendar.resources.none') },
    ...resources.map((r) => ({ value: r.id, label: `${r.name} (${r.type})` })),
  ];

  return (
    <div className="space-y-2" data-testid="resource-booking">
      <div className="text-sm font-medium text-secondary-800">
        {t('calendar.resources.title')}
      </div>
      <div className="flex gap-2">
        <div className="flex-1">
          <Select
            value={resourceId}
            onChange={(e) => setResourceId(e.target.value)}
            options={options}
            data-testid="resource-select"
          />
        </div>
        <Button
          variant="primary"
          size="sm"
          onClick={handleBook}
          isLoading={busy}
          disabled={!resourceId}
          data-testid="resource-book"
        >
          {t('calendar.resources.book')}
        </Button>
      </div>

      {conflict && (
        <div
          className="text-xs text-warning-800 bg-warning-50 border border-warning-200 rounded-md p-2"
          data-testid="resource-conflict"
        >
          {conflict}
        </div>
      )}
      {success && (
        <div
          className="text-xs text-success-700 bg-success-50 border border-success-200 rounded-md p-2"
          data-testid="resource-success"
        >
          {success}
        </div>
      )}
      {error && (
        <div
          className="text-xs text-danger-700 bg-danger-50 border border-danger-200 rounded-md p-2"
          data-testid="resource-error"
        >
          {error}
        </div>
      )}
    </div>
  );
}

export default ResourceBooking;
