"use client"

import { useState, useRef, useEffect } from "react"

export function EditPhotos({ initialPhotos }: { initialPhotos: any[] }) {
  const [existingPhotos, setExistingPhotos] = useState(initialPhotos)
  const [deletedIds, setDeletedIds] = useState<string[]>([])
  const [newFiles, setNewFiles] = useState<{file: File, preview: string}[]>([])
  const hiddenInputRef = useRef<HTMLInputElement>(null)

  const totalPhotos = existingPhotos.length + newFiles.length

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || e.target.files.length === 0) return
    const files = Array.from(e.target.files)
    const validFiles = files.filter((file) => {
      if (file.size > 10 * 1024 * 1024) {
        alert(`Fișierul "${file.name}" depășește limita de 10 MB.`)
        return false
      }
      return true
    })
    
    const remaining = 5 - totalPhotos
    const toProcess = validFiles.slice(0, remaining)

    const newFilesWithPreview = toProcess.map(file => ({
      file,
      preview: URL.createObjectURL(file)
    }))

    setNewFiles(prev => [...prev, ...newFilesWithPreview])
    e.target.value = "" // Reset input
  }

  const handleDeleteExisting = (id: string) => {
    setExistingPhotos(prev => prev.filter(p => p.id !== id))
    setDeletedIds(prev => [...prev, id])
  }

  const handleDeleteNew = (index: number) => {
    setNewFiles(prev => {
      const updated = [...prev]
      URL.revokeObjectURL(updated[index].preview) // cleanup
      updated.splice(index, 1)
      return updated
    })
  }

  // Update the hidden file input with the accumulated files using DataTransfer
  useEffect(() => {
    if (hiddenInputRef.current) {
      const dt = new DataTransfer()
      newFiles.forEach(nf => dt.items.add(nf.file))
      hiddenInputRef.current.files = dt.files
    }
  }, [newFiles])

  return (
    <>
      <input type="hidden" name="deletedPhotoIds" value={deletedIds.join(",")} />
      
      <h3 style={{ fontSize: "1.1rem", color: "var(--primary)", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1.5rem", marginTop: "1.5rem" }}>
        III. Fotografii ({totalPhotos} / 5)
      </h3>

      <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem", marginBottom: "1.5rem" }}>
        {existingPhotos.map((photo: any) => (
          <div key={photo.id} style={{ position: "relative", background: "var(--surface-color)", border: "1px solid var(--border-color)", padding: "1rem", borderRadius: "var(--radius-md)", display: "grid", gridTemplateColumns: "120px 1fr", gap: "1rem", alignItems: "start" }}>
             {/* eslint-disable-next-line @next/next/no-img-element */}
             <img src={photo.url} alt={photo.filename} style={{ width: "120px", height: "90px", objectFit: "cover", display: "block", borderRadius: "var(--radius-sm)" }} />
             
             <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontWeight: 600, fontSize: "0.9rem" }}>{photo.filename}</span>
                  <button
                    type="button"
                    onClick={() => handleDeleteExisting(photo.id)}
                    style={{ color: "var(--danger)", background: "none", border: "none", cursor: "pointer", fontWeight: 700, fontSize: "1.1rem" }}
                  >✕</button>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.5rem" }}>
                  <div>
                    <label style={{ display: "block", fontSize: "0.8rem", color: "var(--text-muted)", marginBottom: "0.25rem" }}>Data realizării *</label>
                    <input type="date" name={`existing_dateOfCapture_${photo.id}`} defaultValue={photo.dateOfCapture ? new Date(photo.dateOfCapture).toISOString().split('T')[0] : ""} required style={{ width: "100%", padding: "0.5rem", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-color)", background: "var(--surface-hover)" }} />
                  </div>
                  <div>
                    <label style={{ display: "block", fontSize: "0.8rem", color: "var(--text-muted)", marginBottom: "0.25rem" }}>Aparatură (Opțional)</label>
                    <input type="text" name={`existing_equipment_${photo.id}`} defaultValue={photo.equipment || ""} maxLength={100} style={{ width: "100%", padding: "0.5rem", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-color)", background: "var(--surface-hover)" }} />
                  </div>
                </div>
                <div>
                  <label style={{ display: "block", fontSize: "0.8rem", color: "var(--text-muted)", marginBottom: "0.25rem" }}>Setări tehnice (Opțional)</label>
                  <input type="text" name={`existing_technicalSettings_${photo.id}`} defaultValue={photo.technicalSettings || ""} maxLength={150} style={{ width: "100%", padding: "0.5rem", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-color)", background: "var(--surface-hover)" }} />
                </div>
             </div>
          </div>
        ))}
        
        {newFiles.map((nf, index) => (
          <div key={`new-${index}`} style={{ position: "relative", background: "var(--surface-color)", border: "2px solid var(--success)", padding: "1rem", borderRadius: "var(--radius-md)", display: "grid", gridTemplateColumns: "120px 1fr", gap: "1rem", alignItems: "start" }}>
             <div style={{ position: "relative" }}>
               {/* eslint-disable-next-line @next/next/no-img-element */}
               <img src={nf.preview} alt={nf.file.name} style={{ width: "120px", height: "90px", objectFit: "cover", display: "block", borderRadius: "var(--radius-sm)" }} />
               <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, background: "rgba(16, 185, 129, 0.9)", color: "white", fontSize: "0.65rem", padding: "2px 4px", textAlign: "center", fontWeight: "bold" }}>NOU</div>
             </div>
             
             <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontWeight: 600, fontSize: "0.9rem" }}>{nf.file.name}</span>
                  <button
                    type="button"
                    onClick={() => handleDeleteNew(index)}
                    style={{ color: "var(--danger)", background: "none", border: "none", cursor: "pointer", fontWeight: 700, fontSize: "1.1rem" }}
                  >✕</button>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.5rem" }}>
                  <div>
                    <label style={{ display: "block", fontSize: "0.8rem", color: "var(--text-muted)", marginBottom: "0.25rem" }}>Data realizării *</label>
                    {/* Native HTML input name works like array for the backend form tracking */}
                    <input type="date" name="new_dateOfCapture" defaultValue={new Date().toISOString().split('T')[0]} required style={{ width: "100%", padding: "0.5rem", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-color)", background: "var(--surface-hover)", color: "var(--text-main)" }} />
                  </div>
                  <div>
                    <label style={{ display: "block", fontSize: "0.8rem", color: "var(--text-muted)", marginBottom: "0.25rem" }}>Aparatură (Opțional)</label>
                    <input type="text" name="new_equipment" maxLength={100} style={{ width: "100%", padding: "0.5rem", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-color)", background: "var(--surface-hover)", color: "var(--text-main)" }} />
                  </div>
                </div>
                <div>
                  <label style={{ display: "block", fontSize: "0.8rem", color: "var(--text-muted)", marginBottom: "0.25rem" }}>Setări tehnice (Opțional)</label>
                  <input type="text" name="new_technicalSettings" maxLength={150} style={{ width: "100%", padding: "0.5rem", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-color)", background: "var(--surface-hover)", color: "var(--text-main)" }} />
                </div>
             </div>
          </div>
        ))}
      </div>

      {totalPhotos < 5 ? (
        <div style={{ marginBottom: "1.5rem" }}>
          <label style={{ display: "inline-flex", alignItems: "center", gap: "0.5rem", padding: "0.5rem 1rem", background: "var(--surface-hover)", border: "1px dashed var(--primary)", color: "var(--primary)", borderRadius: "var(--radius-md)", cursor: "pointer", fontWeight: 600 }}>
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
            Adaugă fotografii
            <input
              type="file"
              accept="image/jpeg,image/png,image/jpg"
              multiple
              onChange={handleFileChange}
              style={{ display: "none" }}
            />
          </label>
        </div>
      ) : (
        <p style={{ color: "var(--text-muted)", fontSize: "0.85rem", marginBottom: "1.5rem" }}>
          Ai atins limita maximă de 5 fotografii per intrare.
        </p>
      )}

      {/* Hidden input to pass multipart DataTransfer files to the Server Action */}
      <input type="file" ref={hiddenInputRef} name="newPhotos" multiple style={{ display: "none" }} />
    </>
  )
}
