'use client'

import type { FolderEntry } from '@/lib/client-types'
import { useSecret } from '@/hooks/useSecret'
import { useFolderEntries } from '@/hooks/useFolderEntries'
import { useUploadOrchestrator } from '@/hooks/useUploadOrchestrator'
import SecretInput from './upload/SecretInput'
import FolderDropzone from './upload/FolderDropzone'
import FolderCard from './upload/FolderCard'
import ActionButtons from './upload/ActionButtons'
import OverwriteConfirmModal from './upload/OverwriteConfirmModal'
import NoChangesModal from './upload/NoChangesModal'
import DriveErrorModal from './upload/DriveErrorModal'

export default function UploadZone() {
  const {
    secret,
    secretError,
    secretVisible,
    isSecretEmpty,
    setSecretError,
    handleSecretChange,
    toggleSecretVisible,
  } = useSecret()

  const {
    entries,
    setEntries,
    updateEntry,
    removeEntry,
    resetEntries,
    allDone,
    hasErrors,
  } = useFolderEntries()

  const {
    isUploading,
    globalError,
    setGlobalError,
    overwriteConfirm,
    setOverwriteConfirm,
    noChangesFolder,
    setNoChangesFolder,
    driveError,
    handleUpload,
    handleDriveContinue,
    handleDriveCancel,
    handleCancel,
    handleReset,
    proceedUpload,
  } = useUploadOrchestrator({
    secret,
    setSecretError,
    entries,
    updateEntry,
    resetEntries,
  })

  const handleFolderSelected = (entry: FolderEntry) => {
    setGlobalError(null)
    setEntries([entry])
  }

  const handleToggleViewer = (index: number) => {
    const entry = entries[index]
    if (entry?.modelUrl) {
      updateEntry(index, { viewerOpen: !entry.viewerOpen })
    }
  }

  const hasPendingOrErrors = entries.some((f) => f.status === 'pending' || f.status === 'error')

  return (
    <div className="w-full max-w-2xl space-y-4">
      <SecretInput
        secret={secret}
        secretVisible={secretVisible}
        secretError={secretError}
        disabled={isUploading}
        onChange={handleSecretChange}
        onToggleVisible={toggleSecretVisible}
      />

      {entries.length === 0 && (
        <div className="space-y-2">
          <p className="text-xs text-gray-400 leading-relaxed text-center">
            Deposez un dossier complet contenant votre modele 3D nomme
            {' '}<span className="font-mono text-gray-200">model.glb</span>
            {' '}ainsi que toutes les textures necessaires.
            {' '}Les textures peuvent etre en
            {' '}<span className="font-mono text-gray-200">.png</span>,
            {' '}<span className="font-mono text-gray-200">.jpg</span>
            {' '}ou <span className="font-mono text-gray-200">.webp</span>.
            {' '}Utilisez un nom simple si la texture s&apos;applique au modele entier, et un nom detaille si elle correspond a une partie precise du modele,
            {' '}par exemple <span className="font-mono text-gray-200">color_fenetre.jpg</span>,
            {' '}<span className="font-mono text-gray-200">roughness_tuyaux.png</span>,
            {' '}<span className="font-mono text-gray-200">normal_dashboard.webp</span>
            {' '}ou <span className="font-mono text-gray-200">opacity_verre.png</span>.
          </p>
          <FolderDropzone
            isUploading={isUploading}
            onFolderSelected={handleFolderSelected}
            onError={setGlobalError}
          />
        </div>
      )}

      {globalError && (
        <p className="text-xs text-red-400 text-center">{globalError}</p>
      )}

      {entries.length > 0 && (
        <div className="space-y-2">
          {entries.map((entry, i) => (
            <FolderCard
              key={i}
              entry={entry}
              index={i}
              onToggleViewer={handleToggleViewer}
              onRemove={removeEntry}
            />
          ))}
        </div>
      )}

      <ActionButtons
        isUploading={isUploading}
        isSecretEmpty={isSecretEmpty}
        hasPendingOrErrors={hasPendingOrErrors}
        allDone={allDone}
        hasErrors={hasErrors}
        onUpload={handleUpload}
        onCancel={handleCancel}
        onReset={handleReset}
      />

      {overwriteConfirm && (
        <OverwriteConfirmModal
          folderName={overwriteConfirm.folderName}
          diffs={overwriteConfirm.diffs}
          onCancel={() => setOverwriteConfirm(null)}
          onConfirm={proceedUpload}
        />
      )}

      {noChangesFolder && (
        <NoChangesModal
          folderName={noChangesFolder}
          onCancel={() => {
            setNoChangesFolder(null)
            handleReset()
          }}
          onModify={() => setNoChangesFolder(null)}
        />
      )}

      {driveError && (
        <DriveErrorModal
          error={driveError.error}
          onCancel={handleDriveCancel}
          onContinue={handleDriveContinue}
        />
      )}
    </div>
  )
}
