'use client';

import React, { useRef, useState, useCallback } from 'react';
import Image from 'next/image';
import Select, { MultiValue, StylesConfig } from 'react-select';
import { ProfileField } from '@/services/profile-sections.service';
import { agentsService } from '@/services/agents.service';
import { FormInput } from './FormInput';
import { FormCheckbox } from './FormCheckbox';
import { FormTextarea } from './FormTextarea';
import { FormSelect } from './FormSelect';
import { TagInput } from './TagInput';

// Type for react-select options
interface SelectOption {
  value: string;
  label: string;
}

interface DynamicFieldProps {
  field: ProfileField;
  value: unknown;
  onChange: (fieldSlug: string, value: unknown) => void;
  error?: string;
}

export default function DynamicField({ field, value, onChange, error }: DynamicFieldProps) {
  const handleChange = (newValue: unknown) => {
    onChange(field.slug, newValue);
  };

  // Safe accessors for field properties that might be null/undefined
  const fieldName = field.name || 'Field';
  const fieldSlug = field.slug || '';
  const fieldPlaceholder = field.placeholder || '';
  const safeOptions = Array.isArray(field.options) ? field.options : [];

  // Safe value coercion helpers
  const safeString = (v: unknown): string => (typeof v === 'string' ? v : '');
  const safeStringArray = (v: unknown): string[] => (Array.isArray(v) ? v.filter((item): item is string => typeof item === 'string') : []);
  const safeNumber = (v: unknown, fallback: number): number => (typeof v === 'number' ? v : fallback);
  const safeFileArray = (v: unknown): UploadedFile[] => (Array.isArray(v) ? v : []);

  const renderField = () => {
    switch (field.fieldType) {
      case 'REPEATER':
        // REPEATER fields store data for repeatable sections - don't render as form input
        return null;

      case 'TEXT':
        return (
          <FormInput
            label={fieldName}
            placeholder={fieldPlaceholder || `Enter ${fieldName.toLowerCase()}`}
            value={safeString(value)}
            onChange={(val: string) => handleChange(val)}
            required={field.isRequired}
            error={error}
            maxLength={field.validation?.maxLength}
          />
        );

      case 'TEXTAREA':
        return (
          <FormTextarea
            label={fieldName}
            placeholder={fieldPlaceholder || `Enter ${fieldName.toLowerCase()}`}
            value={safeString(value)}
            onChange={(val: string) => handleChange(val)}
            required={field.isRequired}
            rows={4}
            maxLength={field.validation?.maxLength}
            error={error}
          />
        );

      case 'NUMBER':
        return (
          <FormInput
            label={fieldName}
            type="number"
            placeholder={fieldPlaceholder || `Enter ${fieldName.toLowerCase()}`}
            value={safeString(value)}
            onChange={(val: string) => handleChange(val)}
            required={field.isRequired}
            error={error}
            min={field.validation?.min}
            max={field.validation?.max}
          />
        );

      case 'DATE':
        return (
          <FormInput
            label={fieldName}
            type="date"
            value={safeString(value)}
            onChange={(val: string) => handleChange(val)}
            required={field.isRequired}
            error={error}
            min={field.validation?.minDate}
            max={field.validation?.maxDate}
          />
        );

      case 'CHECKBOX':
        return (
          <FormCheckbox
            label={fieldName}
            checked={Boolean(value)}
            onChange={(checked: boolean) => handleChange(checked)}
          />
        );

      case 'CHECKBOX_GROUP':
        return (
          <CheckboxGroup
            field={field}
            value={safeStringArray(value)}
            onChange={handleChange}
          />
        );

      case 'RADIO':
        return (
          <RadioGroup
            field={field}
            value={safeString(value)}
            onChange={handleChange}
          />
        );

      case 'SELECT':
        return (
          <FormSelect
            label={fieldName}
            value={safeString(value)}
            onChange={(val: string) => handleChange(val)}
            options={safeOptions.map(opt => ({ value: opt.value, label: opt.label }))}
            placeholder={fieldPlaceholder || `Select ${fieldName.toLowerCase()}`}
          />
        );

      case 'MULTI_SELECT':
        return (
          <MultiSelect
            field={field}
            value={safeStringArray(value)}
            onChange={handleChange}
          />
        );

      case 'RANGE':
        return (
          <RangeSlider
            field={field}
            value={safeNumber(value, field.rangeConfig?.min || 0)}
            onChange={handleChange}
          />
        );

      case 'TAG_INPUT':
        return (
          <div className="mb-4">
            <label className="block text-[14px] font-bold font-serif text-[#00293D] mb-2">
              {fieldName}
              {field.isRequired && <span className="text-red-500 ml-1">*</span>}
            </label>
            <TagInput
              tags={safeStringArray(value)}
              onChange={(tags: string[]) => handleChange(tags)}
              placeholder={fieldPlaceholder || `Add ${fieldName.toLowerCase()}`}
            />
          </div>
        );

      case 'FILE':
      case 'FILE_UPLOAD':
        return (
          <FileUpload
            field={field}
            fieldSlug={fieldSlug}
            value={safeFileArray(value)}
            onChange={handleChange}
          />
        );

      default:
        return (
          <FormInput
            label={fieldName}
            placeholder={fieldPlaceholder || `Enter ${fieldName.toLowerCase()}`}
            value={safeString(value)}
            onChange={(val: string) => handleChange(val)}
            required={field.isRequired}
            error={error}
          />
        );
    }
  };

  // Wrap in try-catch to prevent individual field errors from crashing the entire page
  try {
    const fieldContent = renderField();

    // Don't render anything for null fields (like REPEATER)
    if (fieldContent === null) {
      return null;
    }

    return (
      <div className="dynamic-field" data-field-slug={fieldSlug}>
        {fieldContent}
      </div>
    );
  } catch (err) {
    console.error(`Error rendering field "${fieldName}" (${field.fieldType}):`, err);
    return (
      <div className="dynamic-field p-3 bg-red-50 border border-red-200 rounded-lg" data-field-slug={fieldSlug}>
        <p className="text-sm text-red-600">Failed to render field: {fieldName}</p>
      </div>
    );
  }
}

// Checkbox Group Component
interface CheckboxGroupProps {
  field: ProfileField;
  value: string[];
  onChange: (value: string[]) => void;
}

function CheckboxGroup({ field, value, onChange }: CheckboxGroupProps) {
  const safeValue = Array.isArray(value) ? value : [];
  const safeOptions = Array.isArray(field.options) ? field.options : [];

  const handleToggle = (optionValue: string) => {
    const newValue = safeValue.includes(optionValue)
      ? safeValue.filter(v => v !== optionValue)
      : [...safeValue, optionValue];
    onChange(newValue);
  };

  const columns = field.uiConfig?.columns || 2;

  return (
    <div className="mb-4">
      <label className="block text-[14px] font-bold font-serif text-[#00293D] mb-2">
        {field.name || 'Field'}
        {field.isRequired && <span className="text-red-500 ml-1">*</span>}
      </label>
      <div
        className="grid gap-2"
        style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
      >
        {safeOptions.map((option) => {
          const isChecked = safeValue.includes(option.value);
          return (
            <label key={option.value} className="flex items-center gap-2 cursor-pointer">
              <div className="relative">
                <input
                  type="checkbox"
                  checked={isChecked}
                  onChange={() => handleToggle(option.value)}
                  className="sr-only"
                />
                <div className={`w-4 h-4 rounded border-2 flex items-center justify-center transition-colors ${
                  isChecked
                    ? 'bg-[#E58625] border-[#E58625]'
                    : 'bg-white border-[#00293D]/20'
                }`}>
                  {isChecked && (
                    <svg className="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                    </svg>
                  )}
                </div>
              </div>
              <span className="text-[14px] font-serif text-[#00293D]">{option.label}</span>
            </label>
          );
        })}
      </div>
    </div>
  );
}

// Radio Group Component
interface RadioGroupProps {
  field: ProfileField;
  value: string;
  onChange: (value: string) => void;
}

function RadioGroup({ field, value, onChange }: RadioGroupProps) {
  const safeOptions = Array.isArray(field.options) ? field.options : [];

  return (
    <div className="mb-4">
      <label className="block text-[14px] font-bold font-serif text-[#00293D] mb-2">
        {field.name || 'Field'}
        {field.isRequired && <span className="text-red-500 ml-1">*</span>}
      </label>
      <div className="flex flex-wrap gap-4">
        {safeOptions.map((option) => (
          <label key={option.value} className="flex items-center gap-2 cursor-pointer">
            <input
              type="radio"
              name={field.slug}
              checked={value === option.value}
              onChange={() => onChange(option.value)}
              className="w-4 h-4 border-[#00293D]/20 text-[#E58625] focus:ring-[#E58625]"
            />
            <span className="text-[14px] font-serif text-[#00293D]">{option.label}</span>
          </label>
        ))}
      </div>
    </div>
  );
}

// Multi-Select Component using react-select
interface MultiSelectProps {
  field: ProfileField;
  value: string[];
  onChange: (value: string[]) => void;
}

// Custom styles for react-select to match the design
const multiSelectStyles: StylesConfig<SelectOption, true> = {
  control: (base, state) => ({
    ...base,
    borderRadius: '15px',
    borderColor: state.isFocused ? '#E58625' : 'rgba(0, 41, 61, 0.2)',
    boxShadow: state.isFocused ? '0 0 0 1px #E58625' : 'none',
    padding: '4px',
    minHeight: '48px',
    fontFamily: 'inherit',
    '&:hover': {
      borderColor: '#E58625',
    },
  }),
  placeholder: (base) => ({
    ...base,
    color: 'rgba(0, 41, 61, 0.4)',
    fontSize: '14px',
  }),
  input: (base) => ({
    ...base,
    fontSize: '14px',
    color: '#00293D',
  }),
  multiValue: (base) => ({
    ...base,
    backgroundColor: 'rgba(229, 134, 37, 0.1)',
    borderRadius: '20px',
  }),
  multiValueLabel: (base) => ({
    ...base,
    color: '#E58625',
    fontSize: '12px',
    padding: '4px 8px',
  }),
  multiValueRemove: (base) => ({
    ...base,
    color: '#E58625',
    borderRadius: '0 20px 20px 0',
    '&:hover': {
      backgroundColor: 'rgba(229, 134, 37, 0.2)',
      color: '#E58625',
    },
  }),
  option: (base, state) => ({
    ...base,
    fontSize: '14px',
    color: '#00293D',
    backgroundColor: state.isSelected
      ? 'rgba(229, 134, 37, 0.1)'
      : state.isFocused
      ? 'rgba(229, 134, 37, 0.05)'
      : 'white',
    '&:active': {
      backgroundColor: 'rgba(229, 134, 37, 0.15)',
    },
  }),
  menu: (base) => ({
    ...base,
    borderRadius: '15px',
    overflow: 'hidden',
    boxShadow: '0px 10px 20px rgba(217, 217, 217, 0.5)',
  }),
  menuList: (base) => ({
    ...base,
    padding: '8px',
  }),
};

function MultiSelect({ field, value, onChange }: MultiSelectProps) {
  const safeFieldOptions = Array.isArray(field.options) ? field.options : [];
  const safeValue = Array.isArray(value) ? value : [];

  // Convert field options to react-select format
  const options: SelectOption[] = safeFieldOptions.map(opt => ({
    value: opt.value,
    label: opt.label,
  }));

  // Convert current value to react-select format
  const selectedOptions = options.filter(opt => safeValue.includes(opt.value));

  const handleChange = (newValue: MultiValue<SelectOption>) => {
    onChange(newValue.map(opt => opt.value));
  };

  return (
    <div className="mb-4">
      <label className="block text-[14px] font-bold font-serif text-[#00293D] mb-2">
        {field.name || 'Field'}
        {field.isRequired && <span className="text-red-500 ml-1">*</span>}
      </label>
      <Select<SelectOption, true>
        isMulti
        options={options}
        value={selectedOptions}
        onChange={handleChange}
        placeholder={field.placeholder || `Select ${(field.name || 'option').toLowerCase()}...`}
        styles={multiSelectStyles}
        classNamePrefix="react-select"
        isClearable
        isSearchable
        closeMenuOnSelect={false}
        noOptionsMessage={() => 'No options available'}
      />
    </div>
  );
}

// Range Slider Component
interface RangeSliderProps {
  field: ProfileField;
  value: number;
  onChange: (value: number) => void;
}

function RangeSlider({ field, value, onChange }: RangeSliderProps) {
  const rangeConfig = field.rangeConfig || { min: 0, max: 100, step: 1 };
  const min = rangeConfig.min ?? 0;
  const max = rangeConfig.max ?? 100;
  const step = rangeConfig.step ?? 1;
  const unit = rangeConfig.unit ?? '';

  return (
    <div className="mb-4">
      <label className="block text-[14px] font-bold font-serif text-[#00293D] mb-2">
        {field.name || 'Field'}
        {field.isRequired && <span className="text-red-500 ml-1">*</span>}
      </label>
      <div className="flex items-center gap-4">
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={value}
          onChange={(e) => onChange(Number(e.target.value))}
          className="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-[#E58625]"
        />
        <span className="text-[14px] font-serif text-[#00293D] min-w-[60px] text-right">
          {value}{unit}
        </span>
      </div>
      <div className="flex justify-between text-[12px] text-gray-500 mt-1">
        <span>{min}{unit}</span>
        <span>{max}{unit}</span>
      </div>
    </div>
  );
}

// File Upload Types
interface UploadedFile {
  id: string;
  key?: string; // S3 key for fetching presigned URL
  name: string;
  size: number;
  type: string;
  url: string;
  uploadedAt: string;
}

interface UploadingFile {
  id: string;
  name: string;
  size: number;
  progress: number;
  error?: string;
}

// Map to store presigned URLs by file ID
interface FileWithPresignedUrl extends UploadedFile {
  presignedUrl?: string;
  isLoadingUrl?: boolean;
}

// File Upload Component
interface FileUploadProps {
  field: ProfileField;
  fieldSlug: string;
  value: UploadedFile[];
  onChange: (value: UploadedFile[]) => void;
}

function FileUpload({ field, fieldSlug, value, onChange }: FileUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([]);
  const [presignedUrls, setPresignedUrls] = useState<Record<string, string>>({});
  const [loadingUrls, setLoadingUrls] = useState<Record<string, boolean>>({});

  // Get allowed formats from field config or use defaults
  const validation = field.validation && typeof field.validation === 'object' ? field.validation : {};
  const allowedFormats = Array.isArray(validation.allowedFormats) ? validation.allowedFormats : ['PDF', 'DOCX', 'JPG', 'PNG'];
  const maxFileSize = typeof validation.maxFileSize === 'number' ? validation.maxFileSize : 10; // MB
  const acceptString = allowedFormats.map(f => `.${f.toLowerCase()}`).join(',');

  const formatFileSize = (bytes: number): string => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const formatUploadTime = (dateString: string): string => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);

    if (diffMins < 1) return 'Uploaded just now';
    if (diffMins < 60) return `Uploaded ${diffMins} min ago`;
    const diffHours = Math.floor(diffMins / 60);
    if (diffHours < 24) return `Uploaded ${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
    return `Uploaded on ${date.toLocaleDateString()}`;
  };

  const uploadFile = async (file: File, tempId: string) => {
    try {
      // Import dynamically to avoid SSR issues
      const { uploadService } = await import('@/services/upload.service');

      const uploadedFile = await uploadService.uploadFile(
        file,
        'documents',
        (progress) => {
          setUploadingFiles(prev =>
            prev.map(f =>
              f.id === tempId ? { ...f, progress: progress.percentage } : f
            )
          );
        }
      );

      // Remove from uploading and add to uploaded
      setUploadingFiles(prev => prev.filter(f => f.id !== tempId));
      const newFiles = [...value, uploadedFile];
      onChange(newFiles);

      // Auto-save to database immediately
      try {
        await agentsService.saveFieldValues([{
          fieldSlug: fieldSlug,
          value: newFiles as unknown as Record<string, unknown>[],
        }]);
      } catch (saveError) {
        console.error('Failed to save file to database:', saveError);
        // File is still in S3 and displayed, but database save failed
        // User can manually save later via Save button
      }
    } catch (error) {
      console.error('Upload failed:', error);
      setUploadingFiles(prev =>
        prev.map(f =>
          f.id === tempId ? { ...f, error: 'Upload failed. Please try again.' } : f
        )
      );
    }
  };

  const handleFiles = useCallback(async (files: FileList | null) => {
    if (!files) return;

    const validFiles: { file: File; tempId: string }[] = [];

    Array.from(files).forEach(file => {
      // Check file size
      if (file.size > maxFileSize * 1024 * 1024) {
        alert(`File "${file.name}" exceeds the maximum size of ${maxFileSize}MB`);
        return;
      }

      // Check file type
      const extension = file.name.split('.').pop()?.toUpperCase() || '';
      if (!allowedFormats.includes(extension)) {
        alert(`File type ".${extension}" is not allowed. Allowed formats: ${allowedFormats.join(', ')}`);
        return;
      }

      const tempId = `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
      validFiles.push({ file, tempId });
    });

    if (validFiles.length === 0) return;

    // Add files to uploading state
    setUploadingFiles(prev => [
      ...prev,
      ...validFiles.map(({ file, tempId }) => ({
        id: tempId,
        name: file.name,
        size: file.size,
        progress: 0,
      })),
    ]);

    // Upload each file
    for (const { file, tempId } of validFiles) {
      await uploadFile(file, tempId);
    }
  }, [value, onChange, maxFileSize, allowedFormats]);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    handleFiles(e.dataTransfer.files);
  }, [handleFiles]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleRemoveFile = async (fileId: string) => {
    try {
      // Import dynamically to avoid SSR issues
      const { uploadService } = await import('@/services/upload.service');

      // Try to delete from S3
      await uploadService.deleteFile(fileId);
    } catch (error) {
      console.error('Failed to delete file from server:', error);
      // Continue to remove from local state even if server delete fails
    }

    const newFiles = value.filter(f => f.id !== fileId);
    onChange(newFiles);

    // Auto-save to database immediately
    try {
      await agentsService.saveFieldValues([{
        fieldSlug: fieldSlug,
        value: newFiles as unknown as Record<string, unknown>[],
      }]);
    } catch (saveError) {
      console.error('Failed to save file removal to database:', saveError);
    }
  };

  const handleRemoveUploadingFile = (tempId: string) => {
    setUploadingFiles(prev => prev.filter(f => f.id !== tempId));
  };

  const handleSelectFiles = () => {
    fileInputRef.current?.click();
  };

  const handleViewFile = async (file: UploadedFile) => {
    // Check if we already have a presigned URL
    if (presignedUrls[file.id]) {
      window.open(presignedUrls[file.id], '_blank');
      return;
    }

    // Get the key - either from file.key, file.id, or file.url if it's an S3 key
    const fileKey = file.key || file.id || file.url || '';

    // If the URL is already a full URL (http/https), just open it directly
    if (fileKey.startsWith('http://') || fileKey.startsWith('https://')) {
      window.open(fileKey, '_blank');
      return;
    }

    // Set loading state
    setLoadingUrls(prev => ({ ...prev, [file.id]: true }));

    try {
      const { uploadService } = await import('@/services/upload.service');
      const presignedUrl = await uploadService.getPresignedDownloadUrl(fileKey);

      // Store for future use
      setPresignedUrls(prev => ({ ...prev, [file.id]: presignedUrl }));

      // Open the file
      window.open(presignedUrl, '_blank');
    } catch (error) {
      console.error('Failed to get presigned URL:', error);
      alert('Failed to open file. Please try again.');
    } finally {
      setLoadingUrls(prev => ({ ...prev, [file.id]: false }));
    }
  };

  const isUploading = uploadingFiles.length > 0;

  return (
    <div className="mb-4">
      {/* Upload Area */}
      <div
        className={`border-2 border-dashed rounded-[15px] p-6 text-center transition-colors ${
          isDragging
            ? 'border-[#E58625] bg-[#E58625]/5'
            : 'border-[#00293D]/20 hover:border-[#E58625]/50'
        } ${isUploading ? 'opacity-50 pointer-events-none' : ''}`}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept={acceptString}
          multiple
          onChange={(e) => {
            handleFiles(e.target.files);
            e.target.value = ''; // Reset input
          }}
          className="hidden"
          disabled={isUploading}
        />

        <div className="flex flex-col items-center gap-3">
          <Image
            src="/assets/icons/upload-icon.svg"
            alt="Upload"
            width={32}
            height={32}
            className="opacity-60"
          />
          <div>
            <p className="text-[14px] font-serif text-[#00293D]">
              Click to upload or drag and drop
            </p>
            <p className="text-[12px] text-gray-500 mt-1">
              {allowedFormats.join(', ')} (max. {maxFileSize}MB)
            </p>
          </div>
          <button
            type="button"
            onClick={handleSelectFiles}
            disabled={isUploading}
            className="px-6 py-2 bg-[#E58625] rounded-full text-[14px] font-semibold font-serif text-white hover:bg-[#E58625]/90 transition-colors disabled:opacity-50"
          >
            {isUploading ? 'Uploading...' : 'Select Files'}
          </button>
        </div>
      </div>

      {/* Uploading Files Progress */}
      {uploadingFiles.length > 0 && (
        <div className="mt-4 space-y-2">
          {uploadingFiles.map((file) => (
            <div
              key={file.id}
              className="p-3 bg-blue-50 rounded-[10px] border border-blue-100"
            >
              <div className="flex items-center justify-between mb-2">
                <span className="text-[14px] font-serif text-[#00293D] truncate flex-1">
                  {file.name}
                </span>
                <button
                  type="button"
                  onClick={() => handleRemoveUploadingFile(file.id)}
                  className="text-gray-400 hover:text-red-500 transition-colors ml-2"
                >
                  ×
                </button>
              </div>
              {file.error ? (
                <p className="text-[12px] text-red-500">{file.error}</p>
              ) : (
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-[#E58625] h-2 rounded-full transition-all duration-300"
                    style={{ width: `${file.progress}%` }}
                  />
                </div>
              )}
              <p className="text-[12px] text-gray-500 mt-1">
                {file.error ? '' : `${file.progress}% • ${formatFileSize(file.size)}`}
              </p>
            </div>
          ))}
        </div>
      )}

      {/* Attached Documents List */}
      {value.length > 0 && (
        <div className="mt-4">
          <h4 className="text-[14px] font-serif font-semibold text-[#00293D] mb-3 flex items-center gap-2">
            <Image
              src="/assets/icons/attachment-icon.svg"
              alt="Attached"
              width={16}
              height={16}
            />
            Attached Documents
          </h4>
          <div className="space-y-2">
            {value.map((file) => (
              <div
                key={file.id}
                className="flex items-center justify-between p-3 bg-gray-50 rounded-[10px]"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => handleViewFile(file)}
                      disabled={loadingUrls[file.id]}
                      className="text-[14px] font-serif text-[#E58625] hover:underline truncate text-left disabled:opacity-50"
                    >
                      {loadingUrls[file.id] ? 'Loading...' : file.name}
                    </button>
                    <button
                      type="button"
                      onClick={() => handleRemoveFile(file.id)}
                      className="text-gray-400 hover:text-red-500 transition-colors flex-shrink-0"
                    >
                      ×
                    </button>
                  </div>
                  <p className="text-[12px] text-gray-500">
                    {formatFileSize(file.size)} • {formatUploadTime(file.uploadedAt)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
