"use client"

import type React from "react"

import { useEffect, useState, useRef } from "react"
import FontAwesome from "@/shared/components/fontawesome"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { BaseStyledRow, TrajetStyledRow } from "@/shared/sections/contract/styles"
import { ActionsIconButton, iconButtonStyles, StyledTableContainer } from "@/shared/theme/css"
import { faTrashCan, faCheck, faTimes } from "@fortawesome/free-solid-svg-icons"
import { TableBody, TableCell, IconButton, Table, CircularProgress, TableHead } from "@mui/material"
import ConfirmDialog from "@/shared/components/dialog/confirmDialog"
import { StyledTextField } from "@/shared/components/table/styles"
import SvgColor from "@/shared/components/svg-color"
import { Box, Stack } from "@mui/system"
import TableNoData from "@/shared/components/table/table-no-data"
import type { DocumentDTO } from "@/shared/types/document"
import FileThumbnail, { ACCEPTED_FILE_TYPES } from "@/shared/components/file-thumbnail"
import { dateFormat, formatDate } from "@/utils/format-time"
import { CustomTableSortLabel } from "@/shared/components/table/table-head-custom"
import { DEPO_DOCUMENT_TABLE_HEAD } from "@/shared/_mock/_usagers"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useSortableData } from "@/shared/components/table/use-sortable-data"
import { enqueueSnackbar } from "notistack"
import { useDocumentStore } from "@/shared/api/stores/document-service/documentStore"

interface DepotDocumentFormProps {
  idUser: string
}

export default function DepotDocumentForm({ idUser }: DepotDocumentFormProps) {
  const { documents, loading, error, getUserDocuments, deleteDocument, upload, renameDocument } = useDocumentStore()

  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [documentToDelete, setDocumentToDelete] = useState<number | null>(null)
  const [editingId, setEditingId] = useState<number | null>(null)
  const [editingName, setEditingName] = useState("")
  const fileInputRef = useRef<HTMLInputElement>(null)
  const { sortedData, order, sortBy, handleSort } = useSortableData<DocumentDTO>(documents, {
    initialSortBy: 'createdAt',
    initialOrder: 'asc',
  })
 
  useEffect(() => {
    const fetchDocuments = async () => {
      if (idUser) {
        try {
          await getUserDocuments(idUser)
        } catch (error: any) {
          enqueueSnackbar(error.message || "Erreur lors de la récupération des documents", {
            variant: "error",
          })
        }
      }
    }
    fetchDocuments()
  }, [idUser, getUserDocuments])

  const handleDeleteDocument = (id: number) => {
    setDocumentToDelete(id)
    setDeleteDialogOpen(true)
  }

  const confirmDelete = async () => {
    if (documentToDelete !== null) {
      try {
        await deleteDocument(Number.parseInt(idUser), documentToDelete)
        enqueueSnackbar("Document supprimé avec succès", { variant: "success" })
      } catch (error: any) {
        enqueueSnackbar(error.message || "Erreur lors de la suppression du document", {
          variant: "error",
        })
      }
    }
    setDeleteDialogOpen(false)
    setDocumentToDelete(null)
  }

  const cancelDelete = () => {
    setDeleteDialogOpen(false)
    setDocumentToDelete(null)
  }

  const handleEditDocument = (id: number, currentName: string) => {
    setEditingId(id)
    setEditingName(currentName)
  }

  const handleSaveEdit = async (id: number) => {
    try {
      await renameDocument(idUser, id, editingName)
      await getUserDocuments(idUser)
      enqueueSnackbar("Document renommé avec succès", { variant: "success" })
      setEditingId(null)
      setEditingName("")
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de la modification du nom", {
        variant: "error",
      })
    }
  }


  const handleCancelEdit = () => {
    setEditingId(null)
    setEditingName("")
  }

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

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file && idUser) {
      try {
        await upload(file, idUser)
        await getUserDocuments(idUser)
        enqueueSnackbar("Document uploadé avec succès", { variant: "success" })
      } catch (error: any) {
        enqueueSnackbar(error.message || "Erreur lors de l'upload du document", {
          variant: "error",
        })
      }
    }
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  const handleDownloadDocument = (downloadUrl?: string) => {
    if (downloadUrl) {
      window.open(downloadUrl, "_blank")
    }
  }

  if (loading) {
    return (
      <Stack alignItems="center" justifyContent="center" sx={{ py: 4 }}>
        <CircularProgress />
      </Stack>
    )
  }

  return (
    <>
      <Stack flexGrow={0} direction="row" justifyContent="flex-end">
        <CustomTooltip title="Importer Document" arrow>
          <IconButton disabled={!idUser} size="small" sx={iconButtonStyles} onClick={handleUploadClick}>
            <SvgColor src="/assets/icons/form/ic_upload.svg" sx={{ width: "16px", height: "16px" }} />
          </IconButton>
        </CustomTooltip>
        <input
          type="file"
          ref={fileInputRef}
          onChange={handleFileUpload}
          style={{ display: "none" }}
          accept={ACCEPTED_FILE_TYPES.join(",")}
        />
      </Stack>

      <StyledTableContainer>
        <Table stickyHeader sx={{ mt: 1, minWidth: 960 }}>
          <TableHead>
            <BaseStyledRow>
              {DEPO_DOCUMENT_TABLE_HEAD.map((headCell) => (
                <TableCell
                  sx={{ px: { xs: 1, xl: 2 }, py: 1.5, backgroundColor: "primary.lighter", }}
                  key={headCell.id}
                  align={headCell.align}
                  sortDirection={sortBy === headCell.id ? order : false}
                >
                  <ConditionalComponent isValid={(headCell.id !== 'actions' && headCell.id !== 'downloadUrl')}
                    defaultComponent={<Box component="span" sx={{ color: 'text.disabled' }}> {headCell.label} </Box>}
                  >
                    <CustomTableSortLabel
                      active={sortBy === headCell.id}
                      direction={sortBy === headCell.id ? order : 'asc'}
                      orderBy={sortBy}
                      order={order}
                      onSort={() => handleSort(headCell.id as keyof DocumentDTO)}
                    >
                      {headCell.label}
                    </CustomTableSortLabel>
                  </ConditionalComponent>
                  
                </TableCell>
              ))}
            </BaseStyledRow>
          </TableHead>
          <TableBody>
            <ConditionalComponent
              isValid={sortedData.length > 0}
              defaultComponent={<TableNoData notFound={true} colSpan={4} />}
            >
              {sortedData.map((document: DocumentDTO) => (
                <TrajetStyledRow key={document.id}>
                  <TableCell align="center">{document.createdAt ? formatDate(document.createdAt, dateFormat.isoDate) : "--"}</TableCell>
                  <TableCell align="center">
                    <ConditionalComponent isValid={editingId === document.id}
                      defaultComponent={
                        <div
                          onDoubleClick={() => handleEditDocument(document.id, document.name)}
                          style={{ cursor: 'pointer' }}
                        >
                          {document.name}
                        </div>
                      }
                    >
                      <StyledTextField
                        sx={{ width: "60%" }}
                        value={editingName}
                        onChange={(e) => setEditingName(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            handleSaveEdit(document.id);
                          } else if (e.key === 'Escape') {
                            handleCancelEdit();
                          }
                        }}
                        autoFocus
                      />
                    </ConditionalComponent>
                  </TableCell>
                  <TableCell align="center" sx={{ p: 0 }}>
                    <CustomTooltip title="Télécharger Document" arrow>
                      <IconButton
                        onClick={() => handleDownloadDocument(document.downloadUrl)}
                        size="small"
                        sx={ActionsIconButton}
                        disabled={!document.downloadUrl}
                      >
                        <FileThumbnail file={document.contentType || "PDF"} sx={{ width: 20, height: 20 }} />
                      </IconButton>
                    </CustomTooltip>
                  </TableCell>
                  <TableCell align="center">
                    <ConditionalComponent 
                    isValid={editingId === document.id}
                      defaultComponent={
                        <CustomTooltip title="Delete Document" arrow>
                          <IconButton onClick={() => handleDeleteDocument(document.id)} size="small" sx={ActionsIconButton}>
                            <FontAwesome icon={faTrashCan} width={14} />
                          </IconButton>
                        </CustomTooltip>
                      }
                    >
                      <>
                        <CustomTooltip title="Save" arrow>
                          <IconButton onClick={() => handleSaveEdit(document.id)} size="small" sx={ActionsIconButton}>
                            <FontAwesome icon={faCheck} width={16} />
                          </IconButton>
                        </CustomTooltip>
                        <CustomTooltip title="Cancel" arrow>
                          <IconButton onClick={handleCancelEdit} size="small" sx={ActionsIconButton}>
                            <FontAwesome icon={faTimes} width={16} />
                          </IconButton>
                        </CustomTooltip>
                      </>
                    </ConditionalComponent>
                  </TableCell>
                </TrajetStyledRow>
              ))
              }
            </ConditionalComponent>
          </TableBody>
        </Table>

        <ConfirmDialog
          open={deleteDialogOpen}
          title="Confirm Delete"
          content="Are you sure you want to delete this document?"
          onConfirm={confirmDelete}
          onCancel={cancelDelete}
        />
      </StyledTableContainer>
    </>
  )
}
