import Checkbox from "@mui/material/Checkbox"
import TableCell from "@mui/material/TableCell"
import { type TableColumn } from "@/shared/types/common"
import TableActionColumn from "@/shared/components/table/table-action-column"
import { ContratStyledRow } from "@/shared/sections/contract/styles"
import { type Candidat, type CandidatStatus } from "@/shared/types/candidat"
import SvgColor from "@/shared/components/svg-color"
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import { IconButton, Tooltip, Button, Box, Select, MenuItem } from '@mui/material';
import { useState } from 'react';
import ContractGenerationDialog from '../components/salarie-generation-dialog';
import EditIcon from '@mui/icons-material/Edit';
import DescriptionIcon from '@mui/icons-material/Description';
import { useTheme } from '@mui/material/styles';
import { SalarieStatusChip } from '../styles';
import StatusMenu from "@/shared/components/table/StatusMenu"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

type Props = {
  handleEdit: (candidat: Candidat) => void
  handleDetails: (candidat: Candidat) => void
  handleCopy: (candidat: Candidat) => void
  selected: boolean
  row: Candidat
  dense: boolean
  onSelectRow: VoidFunction
  columns: TableColumn[]
  onStatusChange: (row: Candidat, newStatus: string, field: keyof Candidat) => void;
}

const TOOLTIP_TITLES = {
  edit: "Modifier salarié",
  duplicate: "Copier salarié",
  active: "Salarié actif",
  inactive: "Salarié inactif",
}

const STATUS_OPTIONS: { value: CandidatStatus; label: string }[] = [
  { value: 'Salarié', label: 'Salarié' },
  { value: 'Sorti', label: 'Sorti' },
  { value: 'Archivé', label: 'Archivé' },
];

export default function CandidatTableRow({
  dense,
  row,
  handleEdit,
  handleDetails,
  handleCopy,
  selected,
  onSelectRow,
  columns,
  onStatusChange
}: Props) {
  const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
  const [isContractDialogOpen, setIsContractDialogOpen] = useState(false);
  const theme = useTheme();

  const handleStatusChange = (newStatus: CandidatStatus) => {
    // Handle status update here
    console.log('Status changed to:', newStatus);
  };

  const handleGenerateContract = async () => {
    // Implement contract generation logic
    console.log('Generating contract...');
  };

  const handleSendToDocuSign = async () => {
    // Implement DocuSign integration
    console.log('Sending to DocuSign...');
  };

  const getStatusColor = (status: CandidatStatus) => {
    switch (status) {
      case 'Salarié':
        return 'success.main';
      case 'Sorti':
        return 'warning.main';
      case 'Archivé':
        return 'error.main';
      default:
        return 'text.primary';
    }
  };

  const renderCellContent = (columnId: string, value: any) => {
    if (columnId === 'type') {
      return (
        <Box sx={{ 
          display: 'flex', 
          justifyContent: 'center',
          alignItems: 'center' 
        }}>
          <SalarieStatusChip 
            label={value === 'sedentaire' ? 'Sédentaire' : 'Chauffeur'} 
            status={value} 
            theme={theme} 
            size="small" 
          />
        </Box>
      );
    }
    if (columnId === 'status') {
      return (
          <StatusMenu
            value={value}
            options={STATUS_OPTIONS}
            onChange={(newStatus) => onStatusChange(row, newStatus, 'status')} chipComponent={SalarieStatusChip}
            sx={{width:"120px"}}
          />
      );
    }
    if (columnId === 'cni' || columnId === 'permisConduire' || columnId === 'carteVitale' || columnId === 'rib') {
      return (
        <Tooltip title={value ? "Voir le document" : "Aucun document"}>
          <IconButton size="small" disabled={!value}>
            <InsertDriveFileIcon 
              sx={{ 
                color: value ? 'primary.main' : 'text.disabled',
                fontSize: '1.2rem'
              }} 
            />
          </IconButton>
        </Tooltip>
      );
    }
    return value;
  }

  return (
    <>
      <ContratStyledRow 
        hover 
        onDoubleClick={() => handleDetails(row)}
        style={{ 
          cursor: "pointer",
        }}
      >
        {columns.map((column: TableColumn, index: number) => (
          <TableCell
            key={column.id}
            align={column.align || 'left'}
            sx={{ whiteSpace: 'nowrap',
              ...(index === 0 && {
                position: 'relative',
              })
            }}
          >
            <ConditionalComponent isValid={index === 0}>
            <SvgColor
                src="/assets/icons/ic_border.svg"
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: -4,
                  height: '100%',
                  color: getStatusColor(row.status),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof Candidat])}
          </TableCell>
        ))}

        <TableCell sx={{ px: 1, whiteSpace: "nowrap", py: 0 }}>
          <TableActionColumn
            handleEdit={() => handleEdit(row)}
            onDuplicate={() => handleCopy(row)}
            onToggle={(checked) => console.log("Toggle:", checked)}
            isActive={true}
            tooltipTitles={TOOLTIP_TITLES}
            additionalActions={[
              {
                icon: <DescriptionIcon fontSize="small" />,
                tooltip: "Générer contrat",
                onClick: () => setIsContractDialogOpen(true)
              }
            ]}
          />
        </TableCell>
      </ContratStyledRow>

      <ContractGenerationDialog
        open={isContractDialogOpen}
        onClose={() => setIsContractDialogOpen(false)}
        onGenerate={handleGenerateContract}
        onSendToDocuSign={handleSendToDocuSign}
        candidatName={`${row.prenom} ${row.nom}`}
      />
    </>
  )
}