"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 } from "@fortawesome/free-solid-svg-icons"
import { TableBody, TableCell, IconButton, Table, CircularProgress, TableHead } from "@mui/material"
import ConfirmDialog from "@/shared/components/dialog/confirmDialog"
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 { useCircuitDocumentStore } from "@/shared/api/stores/circuit-service/circuitDocumentStore"

interface CircuitDepotDocumentFormProps {
  circuitId: string
}

export default function CircuitDepotDocumentForm({ circuitId }: CircuitDepotDocumentFormProps) {
  const { 
    documents, 
    loading, 
    error, 
    getCircuitDocuments, 
    deleteDocument, 
    uploadDocument, 
    downloadDocument 
  } = useCircuitDocumentStore()

  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [documentToDelete, setDocumentToDelete] = useState<number | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  
  const { sortedData, order, sortBy, handleSort } = useSortableData<DocumentDTO>(documents, {
    initialSortBy: 'createdAt',
    initialOrder: 'asc',
  })

  useEffect(() => {
    const fetchDocuments = async () => {
      if (circuitId) {
        try {
          await getCircuitDocuments(circuitId)
        } catch (error: any) {
          enqueueSnackbar(error.message || "Erreur lors de la récupération des documents du circuit", {
            variant: "error",
          })
        }
      }
    }
    fetchDocuments()
  }, [circuitId, getCircuitDocuments])

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

  const confirmDelete = async () => {
    if (documentToDelete !== null) {
      try {
        await deleteDocument(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 handleUploadClick = () => {
    fileInputRef.current?.click()
  }

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file && circuitId) {
      try {
        await uploadDocument(file, circuitId)
        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 = async (doc: DocumentDTO) => {
    try {
      const url = await downloadDocument(doc.id)
      const link = document.createElement("a")
      link.href = url
      link.download = doc.name
      document.body.appendChild(link)
      link.click()
      link.remove()
      window.URL.revokeObjectURL(url)
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors du téléchargement", { variant: "error" })
    }
  };
  
  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 Circuit" arrow>
          <IconButton 
            disabled={!circuitId || loading} 
            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">
                    {document.name}
                  </TableCell>
                  <TableCell align="center" sx={{ p: 0 }}>
                    <CustomTooltip title="Télécharger Document" arrow>
                      <IconButton
                        onClick={() => handleDownloadDocument(document)}
                        size="small"
                        sx={ActionsIconButton}
                      >
                        <FileThumbnail 
                          file={document.contentType || "PDF"} 
                          sx={{ width: 20, height: 20 }} 
                        />
                      </IconButton>
                    </CustomTooltip>
                  </TableCell>
                  <TableCell align="center">
                    <CustomTooltip title="Supprimer Document" arrow>
                      <IconButton 
                        onClick={() => handleDeleteDocument(document.id)} 
                        size="small" 
                        sx={ActionsIconButton}
                      >
                        <FontAwesome icon={faTrashCan} width={14} />
                      </IconButton>
                    </CustomTooltip>
                  </TableCell>
                </TrajetStyledRow>
              ))}
            </ConditionalComponent>
          </TableBody>
        </Table>

        <ConfirmDialog
          open={deleteDialogOpen}
          title="Confirmer la suppression"
          content="Êtes-vous sûr de vouloir supprimer ce document du circuit ?"
          onConfirm={confirmDelete}
          onCancel={cancelDelete}
        />
      </StyledTableContainer>
    </>
  )
}
