'use client';

import { useState, useEffect, use, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import ClientSidebar from '@/components/client/ClientSidebar';
import { useToast } from '@/components/ui/ToastContext';
import RichTextarea from '@/components/ui/RichTextarea';
import '@/components/ui/RichTextarea.css';
import './post-project.css';

const projectSchema = z.object({
  title: z.string().min(10, 'Title must be at least 10 characters'),
  categoryId: z.string().min(1, 'Please select a category'),
  budget: z.number().min(1, 'Budget must be at least 1'),
  duration: z.number().min(1, 'Duration must be at least 1 day'),
  // countryId: z.string().min(1, 'Please select a country'),
  city: z.string().optional(),
  zipCode: z.string().optional(),
  description: z.string().min(50, 'Description must be at least 50 characters'),
  attachments: z.any().optional(),
});

type ProjectFormData = z.infer<typeof projectSchema>;

interface PostProjectPageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function PostProjectPage({ params }: PostProjectPageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [isDataLoading, setIsDataLoading] = useState(false);
  const [categories, setCategories] = useState<{id: string; name: string}[]>([]);
  const [countries, setCountries] = useState<{id: string; name: string; code: string}[]>([]);
  const [uploadedFiles, setUploadedFiles] = useState<File[]>([]);
  const [dragActive, setDragActive] = useState(false);
  const [description, setDescription] = useState('');
  const [profileData, setProfileData] = useState<any>('');

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue
  } = useForm<ProjectFormData>({
    resolver: zodResolver(projectSchema)
  });

  const fetchData = useCallback(async () => {
    if (categories.length === 0 && countries.length === 0 && !isDataLoading) {
      setIsDataLoading(true);
      
      try {
        // Fetch categories and countries
        // const [categoriesData, countriesDatam, profileData] = await Promise.all([
        //   fetch('/api/categories').then(res => res.json()),
        //   fetch('/api/countries').then(res => res.json()),
        //   fetch('/api/profile/update').then(res => res.json()),
        // ]);
        const [categoriesData, profileDataGet] = await Promise.all([
          fetch('/api/categories').then(res => res.json()),
          fetch('/api/profile/update').then(res => res.json()),
        ]);

        setCategories(categoriesData || []);
        setProfileData(profileDataGet || '');

      setValue('city', profileDataGet?.user?.profile?.city || '');
      setValue('zipCode', profileDataGet?.user?.profile?.zipCode || '');

       // setCountries(countriesData.countries || []);
        
        // Set default country to Switzerland if available
        // const switzerlandCountry = countriesData.countries?.find((country: {id: string; name: string; code: string}) => 
        //   country.name.toLowerCase() === 'switzerland' || country.code.toLowerCase() === 'ch'
        // );
        // if (switzerlandCountry) {
        //   setValue('countryId', switzerlandCountry.id);
        // }
      } catch (err) {
        console.error('Error fetching data:', err);
        showError('Failed to load data. Please refresh the page.');
      } finally {
        setIsDataLoading(false);
      }
    }
  }, [categories.length, countries.length, isDataLoading, setValue, showError]);

  useEffect(() => {
    if (status === 'loading') return;
    
    if (!session) {
      router.push(`/${locale}/login`);
      return;
    }

    fetchData();
  }, [session, status, locale, router, fetchData]);

  const onSubmit = async (data: ProjectFormData) => {
    setIsLoading(true);

    if(!profileData?.user?.profile?.countryId){
      showError('Country is required', 'Validation Error');
       return false;
    }

    try {
      const formData = new FormData();
      Object.keys(data).forEach(key => {
        if (key !== 'attachments') {
          // Use description state for description field, form data for others
          const value = key === 'description' ? description : (data as Record<string, string | number>)[key];
          formData.append(key, value.toString());
        }
      });

      formData.append('countryId', profileData?.user?.profile?.countryId);
      // Add uploaded files
      uploadedFiles.forEach(file => {
        formData.append('attachments', file);
      });

      const response = await fetch('/api/projects', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to create project');
      }

      await response.json();
      showSuccess('Project posted successfully!', 'Success');
      router.push(`/${locale}/client/my-projects`);
    } catch (err: unknown) {
      const errorMessage = err instanceof Error ? err.message : 'Something went wrong';
      showError(errorMessage, 'Error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleFileUpload = (files: FileList | null) => {
    if (!files) return;
    
    const validTypes = [
      'image/png', 'image/jpeg', 'image/jpg', 'image/gif',
      'application/pdf', 
      'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'text/csv', 'application/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'video/mp4'
    ];
    const maxSize = 10 * 1024 * 1024; // 10MB limit for most files
    const maxVideoSize = 25 * 1024 * 1024; // 25MB limit for video files
    
    const validFiles: File[] = [];
    const invalidFiles: string[] = [];
    
    Array.from(files).forEach(file => {
      if (!validTypes.includes(file.type)) {
        invalidFiles.push(`${file.name} - Invalid file type`);
      } else {
        const isVideo = file.type.startsWith('video/');
        const sizeLimit = isVideo ? maxVideoSize : maxSize;
        const sizeLimitText = isVideo ? '25MB' : '10MB';
        
        if (file.size > sizeLimit) {
          invalidFiles.push(`${file.name} - File too large (max ${sizeLimitText})`);
        } else {
          validFiles.push(file);
        }
      }
    });

    if (invalidFiles.length > 0) {
      showError(`Some files were not uploaded: ${invalidFiles.join(', ')}`, 'Upload Warning');
    }

    if (validFiles.length > 0) {
      setUploadedFiles(prev => [...prev, ...validFiles]);
      showSuccess(`${validFiles.length} file(s) uploaded successfully`, 'Upload Success');
    }
  };

  const removeFile = (index: number) => {
    setUploadedFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleDescriptionChange = (newDescription: string) => {
    setDescription(newDescription);
    // Update the form value for validation
    setValue('description', newDescription, { shouldValidate: true });
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    handleFileUpload(e.dataTransfer.files);
  };

  const getFileIcon = (file: File) => {
    const fileType = file.type.toLowerCase();
    const fileName = file.name.toLowerCase();
    
    // Image files - show actual preview
    if (fileType.startsWith('image/')) {
      return (
        <Image 
          src={URL.createObjectURL(file)} 
          className="rounded" 
          style={{ objectFit: 'cover' }}
          alt="Preview"
          width={160}
          height={160}
        />
      );
    }
    
    // Non-image files - show icon and filename
    let iconColor = '#0E9493';
    let iconText = '';
    
    if (fileType === 'application/pdf') {
      iconText = 'PDF';
      iconColor = '#d32f2f';
    } else if (fileType.includes('word') || fileType.includes('document')) {
      iconText = 'DOC';
      iconColor = '#1976d2';
    } else if (fileType.includes('spreadsheet') || fileType.includes('excel') || fileType.includes('csv')) {
      iconText = 'XLS';
      iconColor = '#388e3c';
    } else if (fileType.startsWith('video/')) {
      iconText = 'MP4';
      iconColor = '#f57c00';
    } else {
      iconText = fileName.split('.').pop()?.toUpperCase() || 'FILE';
    }
    
    return (
      <div className="file-icon-preview d-flex flex-column align-items-center justify-content-center" 
           style={{ width: '200px', height: '200px', backgroundColor: '#f8f9fa', border: '2px dashed #dee2e6', borderRadius: '8px' }}>
        <div className="file-icon mb-2" 
             style={{ 
               width: '60px', 
               height: '60px', 
               backgroundColor: iconColor, 
               borderRadius: '8px',
               display: 'flex',
               alignItems: 'center',
               justifyContent: 'center',
               color: 'white',
               fontSize: '14px',
               fontWeight: 'bold'
             }}>
          {iconText}
        </div>
        <small className="text-muted text-center px-2" style={{ fontSize: '12px', wordBreak: 'break-word' }}>
          {file.name}
        </small>
        <small className="text-muted">
          ({(file.size / (1024 * 1024)).toFixed(1)} MB)
        </small>
      </div>
    );
  };

  if (status === 'loading') {
    return (
      <div className="loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  return (
    <section className="profile-wrapper create-project-wrapper py-60">
      <div className="container">
        <div className="row">
          {/* Sidebar */}
          <div className="col-12 col-md-4 col-xl-3">
            <ClientSidebar locale={locale} />
          </div>

          {/* Main Content */}
          <div className="col-12 col-md-8 col-xl-9">
            <div className="content-box">
              <div className="tab-title">
                <h5>Post A Project</h5>
              </div>

              <div className="form-wrap mt-0">
                <form onSubmit={handleSubmit(onSubmit)}>
                  {/* Project Title */}
                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="title" className="form-label">Project Title <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <input 
                          type="text" 
                          className={`form-control ${errors.title ? 'is-invalid' : ''}`}
                          id="title" 
                          placeholder="Enter Project Title"
                          {...register('title')}
                          disabled={isLoading || isDataLoading}
                        />
                      </div>
                      {errors.title && (
                        <div className="form-text error-text">{errors.title.message}</div>
                      )}
                    </div>
                  </div>

                  {/* Category, Budget, Duration */}
                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="category" className="form-label">Category <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <div className='custom-sub-select'> 
                          <select 
                            id="category"
                            className={`form-control ${errors.categoryId ? 'is-invalid' : ''}`}
                            {...register('categoryId')}
                            disabled={isLoading || isDataLoading}
                            onChange={(e) => {
                              setValue('categoryId', e.target.value);
                            }}
                          >
                            <option value="">Select Category</option>
                            {categories.map((category) => (
                              <option key={category.id} value={category.id}>
                                {category.name}
                              </option>
                            ))}
                          </select>
                        </div>
                      </div>
                      {errors.categoryId && (
                        <div className="form-text error-text">{errors.categoryId.message}</div>
                      )}
                    </div>
                    <div className="mb-20">
                      <label htmlFor="budget" className="form-label">Your Budget <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <input 
                          type="text" 
                          className={`form-control ${errors.budget ? 'is-invalid' : ''}`}
                          id="budget" 
                          placeholder="Enter Budget"
                          {...register('budget', { 
                            valueAsNumber: true,
                            setValueAs: (value) => parseFloat(value) || 0
                          })}
                          disabled={isLoading || isDataLoading}
                        />
                      </div>
                      {errors.budget && (
                        <div className="form-text error-text">{errors.budget.message}</div>
                      )}
                    </div>
                    <div className="mb-20">
                      <label htmlFor="duration" className="form-label">Days needed to complete the work <span className='text-danger'>*</span></label>
                      <div className="input-icon">
                        <input 
                          type="text" 
                          className={`form-control ${errors.duration ? 'is-invalid' : ''}`}
                          id="duration" 
                          placeholder="Enter Days"
                          {...register('duration', { 
                            valueAsNumber: true,
                            setValueAs: (value) => parseInt(value) || 0
                          })}
                          disabled={isLoading || isDataLoading}
                        />
                      </div>
                      {errors.duration && (
                        <div className="form-text error-text">{errors.duration.message}</div>
                      )}
                    </div>
                  </div>
                  
                  {/* Location */}
                  <div className="form-group no-icon-box">
                    {/* <div className="mb-20">
                      <label htmlFor="countryId" className="form-label">Country</label>
                      <div className="input-icon">
                        <div className='custom-sub-select'> 
                          <select 
                            id="countrySelect"
                            className={`form-control ${errors.countryId ? 'is-invalid' : ''}`}
                            {...register('countryId')}
                            disabled={isLoading || isDataLoading}
                          >
                            <option value="">Select a country</option>
                            {countries.map((country) => (
                              <option key={country.id} value={country.id}>
                                {country.name}
                              </option>
                            ))}
                          </select>
                        </div>
                      </div>
                      {errors.countryId && (
                        <div className="form-text error-text">{errors.countryId.message}</div>
                      )}
                    </div> */}
                    <div className="mb-20">
                      <label htmlFor="city" className="form-label">City</label>
                      <div className="input-icon">
                        <input 
                          type="text" 
                          className="form-control"
                          id="city" 
                          placeholder="Enter City"
                          {...register('city')}
                          disabled={isLoading || isDataLoading}
                        />
                      </div>
                    </div>
                    <div className="mb-20 no-icon-box">
                      <label htmlFor="zipCode" className="form-label">Zip Code</label>
                      <div className="input-icon">
                        <input 
                          type="number" 
                          className="form-control"
                          id="zipCode" 
                          placeholder="Enter Zip Code"
                          {...register('zipCode')}
                          disabled={isLoading || isDataLoading}
                        />
                      </div>
                    </div>
                  </div>

                  {/* Description */}
                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="description" className="form-label">Description</label>
                    </div>
                  </div>
                  <div className="form-group">
                    <div className="mb-20">
                      <div className="input-icon">
                        <RichTextarea
                          value={description}
                          onChange={handleDescriptionChange}
                          placeholder="Describe your project in detail, including requirements, goals, timeline, and any specific details that will help freelancers understand your needs..."
                          disabled={isLoading || isDataLoading}
                          minHeight="160px"
                          className={`form-control ${errors.description ? 'is-invalid' : ''}`}
                          rows={6}
                        />
                      </div>
                      {errors.description && (
                        <div className="form-text error-text">{errors.description.message}</div>
                      )}
                    </div>
                  </div>

                  {/* File Upload */}
                  <div className="form-group">
                    <div className="mb-20">
                      <div className="upload-outer">
                        <label className="form-label fw-semibold">Upload Documents</label>
                        <div 
                          className={`upload-area position-relative ${dragActive ? 'drag-active' : ''}`}
                          id="uploadArea"
                          onDragEnter={handleDrag}
                          onDragLeave={handleDrag}
                          onDragOver={handleDrag}
                          onDrop={handleDrop}
                          onClick={() => document.getElementById('fileInput')?.click()}
                        >
                          {/* {uploadedFiles.length > 0 && uploadedFiles[0] && (
                            <div id="previewBox" className="position-relative d-inline-block">
                              {getFileIcon(uploadedFiles[0])}
                              <div className="position-absolute" style={{ top: '5px', right: '5px' }}>
                                <button 
                                  type="button" 
                                  className="btn btn-sm me-1" 
                                  style={{ backgroundColor: 'rgba(255,255,255,0.9)', border: '1px solid #ccc' }}
                                  title="Download"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    const file = uploadedFiles[0];
                                    const url = URL.createObjectURL(file);
                                    const a = document.createElement('a');
                                    a.href = url;
                                    a.download = file.name;
                                    document.body.appendChild(a);
                                    a.click();
                                    document.body.removeChild(a);
                                    URL.revokeObjectURL(url);
                                  }}
                                >
                                  <span className="text-primary fw-bold">↓</span>
                                </button>
                                <button 
                                  type="button" 
                                  className="btn btn-sm" 
                                  style={{ backgroundColor: 'rgba(255,255,255,0.9)', border: '1px solid #ccc' }}
                                  title="Remove"
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    removeFile(0);
                                  }}
                                >
                                  <span className="text-danger fs-5 fw-bold">×</span>
                                </button>
                              </div>
                            </div>
                          )} */}
                          {/* {uploadedFiles.length === 0 && ( */}
                            <div id="placeholder" className="upload-placeholder">
                              <svg width="69" height="60" viewBox="0 0 69 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M46.208 5.70117C46.6948 5.70117 47.0897 6.09627 47.0898 6.58301C47.0898 7.06987 46.6949 7.46484 46.208 7.46484C42.0957 7.46495 38.405 10.2157 37.2334 14.1523C37.1047 14.5864 36.6701 14.848 36.2324 14.7686L36.2285 14.7734L36.1367 14.7461C35.6703 14.607 35.4039 14.1162 35.543 13.6494C36.9067 9.06679 41.154 5.70127 46.208 5.70117Z" fill="#0E9493" stroke="#787676" strokeWidth="0.3"/>
                                <path d="M56.4522 42.4384H52.0618C51.6578 42.4384 51.3301 42.1107 51.3301 41.7067C51.3301 41.3027 51.6578 40.9749 52.0618 40.9749H56.4522C62.504 40.9749 67.4281 36.0509 67.4281 29.999C67.4281 23.9471 62.504 19.023 56.4522 19.023H56.3466C56.1344 19.023 55.9326 18.9311 55.7936 18.7706C55.6546 18.6101 55.5918 18.3974 55.6222 18.1873C55.6875 17.7315 55.7204 17.2737 55.7204 16.8279C55.7204 11.5829 51.4528 7.31531 46.2079 7.31531C44.1674 7.31531 42.2215 7.95296 40.5803 9.15978C40.2196 9.42478 39.7074 9.30718 39.4989 8.91047C34.8509 0.0596993 22.7107 -1.12887 16.4166 6.57053C13.7652 9.81417 12.7234 14.0336 13.5582 18.146C13.6502 18.6002 13.3026 19.0236 12.8411 19.0236H12.5479C6.496 19.0236 1.57193 23.9477 1.57193 29.9996C1.57193 36.0514 6.496 40.9755 12.5479 40.9755H16.9382C17.3422 40.9755 17.6699 41.3032 17.6699 41.7072C17.6699 42.1113 17.3422 42.439 16.9382 42.439H12.5479C5.6889 42.439 0.108398 36.8585 0.108398 29.9995C0.108398 23.3329 5.37995 17.8742 11.9735 17.5731C11.3541 13.3066 12.5385 9.00295 15.2835 5.64437C22.0222 -2.5996 34.9364 -1.67556 40.3955 7.51707C42.1371 6.42522 44.1299 5.85244 46.2076 5.85244C52.5622 5.85244 57.5976 11.261 57.157 17.58C63.6897 17.9463 68.8913 23.3763 68.8913 29.999C68.8913 36.8585 63.3108 42.4384 56.4518 42.4384L56.4522 42.4384Z" fill="#0E9493"/>
                                <path d="M34.4023 22.8496C44.5721 22.8499 52.8457 31.1242 52.8457 41.2939C52.8454 51.4634 44.5719 59.7371 34.4023 59.7373C24.2327 59.7373 15.9583 51.4637 15.958 41.2939C15.958 31.1241 24.2324 22.8496 34.4023 22.8496ZM34.4023 24.6143C25.2053 24.6143 17.7227 32.097 17.7227 41.2939C17.7229 50.4908 25.2056 57.9736 34.4023 57.9736C43.5989 57.9734 51.0818 50.4905 51.082 41.2939C51.082 32.0971 43.599 24.6145 34.4023 24.6143Z" fill="#0E9493" stroke="#787676" strokeWidth="0.3"/>
                                <path d="M34.7368 34.043C35.1153 34.0432 35.4224 34.351 35.4224 34.7295V48.6572C35.4224 49.0362 35.1152 49.3435 34.7368 49.3438C34.3582 49.3438 34.0503 49.0359 34.0503 48.6572V34.7295C34.0503 34.3509 34.3582 34.043 34.7368 34.043Z" fill="#0E9493" stroke="#0E9493" strokeWidth="0.3"/>
                                <path d="M34.252 34.2461C34.5196 33.9784 34.954 33.9784 35.2217 34.2461L39.5068 38.5322C39.7746 38.8001 39.7747 39.2341 39.5068 39.502L39.5059 39.501C39.372 39.6351 39.197 39.7021 39.0225 39.7021C38.8474 39.7021 38.6708 39.6356 38.5371 39.502L34.7363 35.7002L30.9355 39.502C30.668 39.7696 30.2335 39.7696 29.9658 39.502C29.698 39.2342 29.6982 38.8001 29.9658 38.5322L34.252 34.2461Z" fill="#0E9493" stroke="#0E9493" strokeWidth="0.3"/>
                              </svg>
                              <p>Drag & drop files or <a href="#" className="text-decoration-none">Browse</a></p>
                              <small className="text-muted">Supported formats: .jpg, .jpeg, .png, .gif, .pdf, .doc, .docx, .csv, .xls, .xlsx, .mp4 (max 10MB, videos 25MB)</small>
                            </div>
                           {/* )} */}
                          <input
                            type="file"
                            className="d-none"
                            id="fileInput"
                            accept="image/png, image/jpeg, image/jpg, image/gif, application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/csv, application/csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, video/mp4"
                            multiple
                            onChange={(e) => handleFileUpload(e.target.files)}
                          />
                        </div>
                      </div>
                      
                      {/* {uploadedFiles.length > 1 && ( */}
                      {uploadedFiles.length > 0 && (
                        <div className="uploaded-files mt-3">
                          {/* <h6 className="mb-2">Additional Files ({uploadedFiles.length - 1})</h6> */}
                          <h6 className="mb-2">Additional Files ({uploadedFiles.length})</h6>
                          {/* {uploadedFiles.slice(1).map((file, index) => { */}
                          {uploadedFiles.map((file, index) => {
                            const fileType = file.type.toLowerCase();
                            const fileSize = (file.size / (1024 * 1024)).toFixed(1);
                            let iconColor = '#0E9493';
                            let iconText = '';
                            
                            if (fileType === 'application/pdf') {
                              iconText = 'PDF';
                              iconColor = '#d32f2f';
                            } else if (fileType.includes('word') || fileType.includes('document')) {
                              iconText = 'DOC';
                              iconColor = '#1976d2';
                            } else if (fileType.includes('spreadsheet') || fileType.includes('excel') || fileType.includes('csv')) {
                              iconText = 'XLS';
                              iconColor = '#388e3c';
                            } else if (fileType.startsWith('video/')) {
                              iconText = 'MP4';
                              iconColor = '#f57c00';
                            } else if (fileType.startsWith('image/')) {
                              iconText = 'IMG';
                              iconColor = '#9c27b0';
                            } else {
                              iconText = file.name.split('.').pop()?.toUpperCase() || 'FILE';
                            }
                            
                            return (
                              <div key={index + 1} className="file-item d-flex align-items-center justify-content-between p-2 mb-2 border rounded">
                                <div className="d-flex align-items-center">
                                  <div className="file-type-icon me-3" 
                                       style={{ 
                                         width: '40px', 
                                         height: '40px', 
                                         backgroundColor: iconColor, 
                                         borderRadius: '6px',
                                         display: 'flex',
                                         alignItems: 'center',
                                         justifyContent: 'center',
                                         color: 'white',
                                         fontSize: '12px',
                                         fontWeight: 'bold'
                                       }}>
                                    {iconText}
                                  </div>
                                  <div className="file-details">
                                    <div className="file-name fw-medium" style={{ fontSize: '14px' }}>{file.name}</div>
                                    <small className="text-muted">{fileSize} MB</small>
                                  </div>
                                </div>
                                <div className="file-actions d-flex align-items-center">
                                  <button 
                                    type="button" 
                                    className="btn btn-sm btn-outline-primary me-2"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      e.stopPropagation();
                                      const url = URL.createObjectURL(file);
                                      const a = document.createElement('a');
                                      a.href = url;
                                      a.download = file.name;
                                      document.body.appendChild(a);
                                      a.click();
                                      document.body.removeChild(a);
                                      URL.revokeObjectURL(url);
                                    }}
                                    title="Download"
                                  >
                                    ↓
                                  </button>
                                  <button 
                                    type="button" 
                                    className="btn btn-sm btn-outline-danger"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      e.stopPropagation();
                                      removeFile(index + 1);
                                    }}
                                    title="Remove"
                                  >
                                    ×
                                  </button>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                  
                  <button 
                    type="submit" 
                    className="w-100 custom-btn secondary-btn"
                    disabled={isLoading || isDataLoading}
                  >
                    {isLoading ? 'Creating Project...' : isDataLoading ? 'Loading...' : 'Create Project'}
                  </button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
} 