'use client';

import { NumberField, TextareaField, TextField, TimeField } from '@/components/shared/data-fields';
import { useServiceMutation, useServiceQuery } from '@/hooks/api/services';
import { Button } from '@repo/ui/components/ui/button';
import { Card } from '@repo/ui/components/ui/card';
import { convertTimeString } from '@repo/utils/datetime-format';
import { useState } from 'react';

type Props = {
  serviceId: string;
};

export function ServiceDataCard({ serviceId }: Readonly<Props>) {
  const { data: { service } = {} } = useServiceQuery({ documentId: serviceId });
  const { cancelChanges, hasChanges, isPending, resetTrigger, saveChanges, updateField } =
    useServiceEdit(serviceId);

  if (!service) return null;

  return (
    <Card className="p-4">
      <div className="flex flex-col gap-4">
        <TextField
          id="name"
          key={`name-${resetTrigger}`}
          label="Название"
          onChange={(name) => updateField('name', name)}
          value={service?.name ?? ''}
        />
        <TimeField
          id="duration"
          key={`duration-${resetTrigger}`}
          label="Длительность"
          onChange={(time) => updateField('duration', convertTimeString(time).db())}
          value={service?.duration ?? ''}
        />
        <NumberField
          id="price"
          key={`price-${resetTrigger}`}
          label="Цена (₽)"
          min={0}
          onChange={(price) => updateField('price', price)}
          value={service?.price ?? null}
        />
        <TextareaField
          id="description"
          key={`description-${resetTrigger}`}
          label="Описание"
          onChange={(description) => updateField('description', description)}
          rows={4}
          value={service?.description ?? ''}
        />
        {hasChanges && (
          <div className="flex justify-end gap-2">
            <Button disabled={isPending} onClick={cancelChanges} variant="outline">
              Отмена
            </Button>
            <Button disabled={isPending} onClick={saveChanges}>
              {isPending ? 'Сохранение...' : 'Сохранить'}
            </Button>
          </div>
        )}
      </div>
    </Card>
  );
}

function useServiceEdit(serviceId: string) {
  const { isPending, mutate } = useServiceMutation({ documentId: serviceId });
  const [pendingChanges, setPendingChanges] = useState<Record<string, unknown>>({});
  const [resetTrigger, setResetTrigger] = useState(0);

  const updateField = (field: string, value: unknown) => {
    setPendingChanges((previous) => ({ ...previous, [field]: value }));
  };

  const saveChanges = () => {
    if (Object.keys(pendingChanges).length === 0) return;

    mutate({ data: pendingChanges });
    setPendingChanges({});
  };

  const cancelChanges = () => {
    setPendingChanges({});
    setResetTrigger((previous) => previous + 1);
  };

  const hasChanges = Object.keys(pendingChanges).length > 0;

  return {
    cancelChanges,
    hasChanges,
    isPending,
    resetTrigger,
    saveChanges,
    updateField,
  };
}
