import React, { useState } from 'react';
import { Checkbox, TableRow, TableCell, Chip, Stack, Typography, IconButton , Button, Dialog, DialogTitle, DialogContent, DialogActions, MenuItem, Select, FormControl, InputLabel, SelectChangeEvent } from '@mui/material';
import { IBesoinRecrutement, BesoinRecrutementStatut, BesoinRecrutementTab } from '@/shared/types/besoin-recrutement';
import { TableColumn } from '@/shared/types/common';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCheck, faUserPlus, faEye, faPen, faThumbsUp, faCheckCircle } from '@fortawesome/free-solid-svg-icons';
import { _candidatures } from '@/shared/_mock/_candidature';
import { ContratStyledRow } from '@/shared/sections/contract/styles';
import SvgColor from '@/shared/components/svg-color';
import { styled } from '@mui/system';
import { ActionsIconButton } from '@/shared/theme/css';
import StatusChangeDialog, { StatusOption } from '@/shared/components/dialog/StatusChangeDialog';
import StatusMenu from '@/shared/components/table/StatusMenu';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import TableActionColumn from '@/shared/components/table/table-action-column';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface BesoinRecrutementTableRowProps {
  row: IBesoinRecrutement;
  selected: boolean;
  onSelectRow: VoidFunction;
  handleEdit: (item: IBesoinRecrutement) => void;
  handleView: (item: IBesoinRecrutement) => void;
  columns: TableColumn[];
  dense: boolean;
  activeTab?: BesoinRecrutementTab;
  onStatusChange: (row: IBesoinRecrutement, newStatus: string, field: keyof IBesoinRecrutement) => void;
}

const TOOLTIP_TITLES = {
  edit: "Modifier",
  active: "active",
  inactive: "inactive",
}

const StyledChip = styled(Chip)(({ status }: { status: string }) => ({
  '&.MuiChip-root': {
    fontWeight: 500,
    borderRadius: '8px',
    padding: '9px 0',
    height: '100%',
    width: '100%',
    ...(status === BesoinRecrutementStatut.EnAttente && {
      backgroundColor: '#FEF8E7',
      color: '#F9B90B',
    }),
    ...(status === BesoinRecrutementStatut.EnCours && {
      backgroundColor: '#E3F2FD',
      color: '#0288d1',
    }),
    ...(status === BesoinRecrutementStatut.Traite && {
      backgroundColor: '#E9FBF0',
      color: '#36B37E',
    }),
  },
}));

export default function BesoinRecrutementTableRow({
  row,
  selected,
  onSelectRow,
  handleEdit,
  handleView,
  columns,
  dense,
  activeTab,
  onStatusChange
}: BesoinRecrutementTableRowProps) {
  const [associerModalOpen, setAssocierModalOpen] = useState(false);
  const [selectedCandidatureId, setSelectedCandidatureId] = useState(row.candidatureAssocieeId || '');
  const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);

  const STATUS_OPTIONS = [
    { value: BesoinRecrutementStatut.EnAttente, label: 'En attente' },
    { value: BesoinRecrutementStatut.EnCours, label: 'En cours' },
    { value: BesoinRecrutementStatut.Traite, label: 'Traitée' },
  ];

  const getStatusHexColor = (status: BesoinRecrutementStatut) => {
    switch (status) {
      case BesoinRecrutementStatut.EnAttente:
        return '#ff9800'; // warning hex
      case BesoinRecrutementStatut.EnCours:
        return '#0288d1'; // info hex
      case BesoinRecrutementStatut.Traite:
        return '#2e7d32'; // success hex
      default:
        return '#757575'; // default hex
    }
  };

  const getStatusLabel = (status: BesoinRecrutementStatut) => {
    switch (status) {
      case BesoinRecrutementStatut.EnAttente:
        return 'En attente';
      case BesoinRecrutementStatut.EnCours:
        return 'En cours';
      case BesoinRecrutementStatut.Traite:
        return 'Traitée';
      default:
        return status;
    }
  };

  const handleValider = () => {
    const updatedBesoin = {
      ...row,
      statut: BesoinRecrutementStatut.EnCours
    };
    handleEdit(updatedBesoin);
  };

  const handleMarquerTraite = () => {
    const updatedBesoin = {
      ...row,
      statut: BesoinRecrutementStatut.Traite
    };
    handleEdit(updatedBesoin);
  };

  const handleOpenAssocierModal = () => {
    setAssocierModalOpen(true);
  };

  const handleCloseAssocierModal = () => {
    setAssocierModalOpen(false);
  };

  const handleAssocierCandidature = () => {
    if (selectedCandidatureId) {
      const updatedBesoin = {
        ...row,
        candidatureAssocieeId: selectedCandidatureId,
        statut: BesoinRecrutementStatut.Traite
      };
      handleEdit(updatedBesoin);
      setAssocierModalOpen(false);
    }
  };

  const handleCandidatureChange = (event: SelectChangeEvent<string>) => {
    setSelectedCandidatureId(event.target.value);
  };

  const renderCell = (column: TableColumn) => {
    const value = row[column.id as keyof IBesoinRecrutement];

    switch (column.id) {
      case 'demandeur':
        return (
          <Stack direction="row" alignItems="center" spacing={2}>
            <Typography variant="body2" noWrap>
              {row.demandeur}
            </Typography>
          </Stack>
        );
        
      case 'motif':
        return (
          <Typography variant="body2" noWrap>
            {row.motif}
          </Typography>
        );
        
      case 'nombrePostes':
        return (
          <Typography variant="body2" noWrap>
            {row.nombrePostes}
          </Typography>
        );
        
      case 'departement':
        return (
          <Typography variant="body2" noWrap>
            {row.departement}
          </Typography>
        );
        
      case 'circuit':
        return (
          <Typography variant="body2" noWrap>
            {row.circuit}
          </Typography>
        );
        
      case 'dateCreation':
        return (
          <Typography variant="body2" noWrap>
            {row.dateCreation}
          </Typography>
        );
        
      case 'statut':
                return (
                  <StatusMenu
                    value={row.statut}
                    options={STATUS_OPTIONS}
                    onChange={(newStatus) => onStatusChange(row, newStatus, 'statut' as keyof IBesoinRecrutement)}
                    chipComponent={(props) => <StyledChip status={props.value} {...props} />}
                  />
                );
      case 'candidatureAssocieeId':
        if (row.candidatureAssocieeId) {
          const candidature = _candidatures.find(c => c.id === row.candidatureAssocieeId);
          return (
            <Typography variant="body2" noWrap>
              {candidature ? `${candidature.nom} ${candidature.prenom}` : 'Non trouvée'}
            </Typography>
          );
        }
        // Fall through to default if no candidatureAssocieeId
        
      default:
        return (
          <Typography variant="body2" noWrap>
            {value !== null && typeof value !== 'undefined' ? String(value) : ''}
          </Typography>
        );
    }
  };

  return (
    <>
      <ContratStyledRow hover onDoubleClick={() => handleView(row)} style={{ cursor: 'pointer' }}>
        {columns.map((column,index:number) => (
          <TableCell 
            key={column.id} 
            align={column.align || 'left'}
            sx={{ 
              whiteSpace: 'nowrap', 
              py: column.id === 'statut' ? 0.2 : dense ? 1 : 2,
              ...(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: getStatusHexColor(row.statut),
                }}
              />
            </ConditionalComponent>
            {renderCell(column)}
          </TableCell>
        ))}

        <TableCell
          sx={{
            display: 'flex',
            justifyContent: 'flex-start',
            alignItems: 'center',
            py: dense ? 1 : 2
          }}
        >
              <TableActionColumn
                handleEdit={() => handleEdit(row)}
                tooltipTitles={TOOLTIP_TITLES}
              />
        </TableCell>
      </ContratStyledRow>

   
    </>
  );
} 