'use client';

import React, { useState } from 'react';
import { Camera, FileText } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { PhotoDropzone, SectionCard } from '@/components/teltoinstall/_index';
import { usePhotosStep } from '@/hooks/teltoinstall/_index';
import { PhotoType } from '@/models/teltoinstall/_index';
import { WIZARD_FORM_ID } from '../constants';

interface Props {
  onNext: () => void;
}

const PHOTO_CONFIGS: { type: PhotoType; max: number; required?: boolean; requiredError?: string }[] = [
  { type: 'vin', max: 3, required: true, requiredError: 'errors.photoVinRequired' },
  { type: 'before_install', max: 3 },
  { type: 'after_install', max: 3 },
  { type: 'odometer', max: 3, required: true, requiredError: 'errors.photoOdometerRequired' },
  { type: 'device_position', max: 3 },
  { type: 'incident', max: 5 },
];

export default function PhotosStep({ onNext }: Props) {
  const { t } = useTranslation();
  const { photos, notes, uploading, uploadError, addFiles, deletePhoto, savePhotosStep, updateNotes } =
    usePhotosStep();
  const [errors, setErrors] = useState<Partial<Record<PhotoType, string>>>({});

  function handleDelete(index: number, type: PhotoType) {
    const typePhotos = photos.filter((p) => p.type === type);
    const globalIndex = photos.findIndex((p) => p === typePhotos[index]);
    if (globalIndex !== -1) deletePhoto(globalIndex);
  }

  function validateRequired(): boolean {
    const nextErrors: Partial<Record<PhotoType, string>> = {};
    for (const { type, required, requiredError } of PHOTO_CONFIGS) {
      if (required && requiredError && !photos.some((p) => p.type === type)) {
        nextErrors[type] = requiredError;
      }
    }
    setErrors(nextErrors);
    const firstError = Object.values(nextErrors)[0];
    if (firstError) toast.error(t(firstError));
    return Object.keys(nextErrors).length === 0;
  }

  return (
    <form
      id={WIZARD_FORM_ID}
      onSubmit={async (e) => {
        e.preventDefault();
        if (!validateRequired()) return;
        const ok = await savePhotosStep();
        if (ok) onNext();
      }}
    >
      {uploadError && (
        <div className="flex items-center gap-2 p-3 mb-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-sm text-red-600">{uploadError}</p>
        </div>
      )}
      {uploading && (
        <div className="flex items-center gap-2 p-3 mb-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
          <p className="text-sm text-blue-700">{t('wizard.saving')}</p>
        </div>
      )}

      <SectionCard icon={<Camera className="w-4 h-4" />} title={t('photos.sectionTitle')} noPadding>
        <div>
          {PHOTO_CONFIGS.map(({ type, max, required }) => (
            <PhotoDropzone
              key={type}
              type={type}
              photos={photos}
              maxFiles={max}
              required={required}
              error={errors[type] ? t(errors[type]!) : undefined}
              onDrop={(files, photoType) => {
                addFiles(files, photoType);
                setErrors((prev) => ({ ...prev, [photoType]: undefined }));
              }}
              onDelete={(i) => handleDelete(i, type)}
              label={`${t(`photos.${type}`)}${max ? ` (${max} max)` : ''}`}
            />
          ))}
        </div>
      </SectionCard>

      <SectionCard icon={<FileText className="w-4 h-4" />} title={t('photos.sectionComments')}>
        <textarea
          className="field-input min-h-[100px] resize-none"
          placeholder={t('photos.notesPlaceholder')}
          value={notes}
          onChange={(e) => updateNotes(e.target.value)}
        />
      </SectionCard>
    </form>
  );
}
