import React, { useState } from 'react';
import { Checkbox, TableCell, Chip, Stack, Typography, IconButton, TextField, Dialog, DialogTitle, DialogContent, DialogActions, Button, Select, MenuItem, FormControl, InputLabel, useTheme } from '@mui/material';
import { ICandidature, CandidatureStatut, CandidatureTab, CandidatureContratStatut } from '@/shared/types/candidature';
import { TableColumn } from '@/shared/types/common';
import TableActionColumn from '@/shared/components/table/table-action-column';
import SendFormModal from '../send-form-modal';
import SendEmailModal from '../send-email-modal';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCircleCheck} from '@fortawesome/free-regular-svg-icons';
import { faEnvelope, faFileLines, faPlus, faCalendarPlus } from '@fortawesome/free-solid-svg-icons';
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 CustomDatePicker from '@/shared/components/date-picker/customDate';
import dayjs from 'dayjs';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import StatusMenu from '@/shared/components/table/StatusMenu';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';

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

const StyledChip = styled(Chip)(({ status }: { status: string }) => ({
  '&.MuiChip-root': {
    fontWeight: 500,
    borderRadius: '8px',
    padding: '9px 0',
    height: '100%',
    width: '100%',
    ...(status === CandidatureStatut.ATraiter && {
      backgroundColor: '#746CD4',
      color: '#FFFFFF',
    }),
    ...(status === CandidatureStatut.EnCours && {
      backgroundColor: '#E3F2FD',
      color: '#0288d1',
    }),
    ...(status === CandidatureStatut.Retenu && {
      backgroundColor: '#FFF7E0',
      color: '#B78103',
    }),
    ...((status === CandidatureStatut.Valide || status === CandidatureContratStatut.Signe) && {
      backgroundColor: '#E9FBF0',
      color: '#36B37E',
    }),
    ...((status === CandidatureStatut.Refuse || status === CandidatureContratStatut.NonSigne) && {
      backgroundColor: '#FFE1E1',
      color: '#d32f2f',
    }),
    ...(status === CandidatureStatut.Blackliste && {
      backgroundColor: '#2D2D2D',
      color: '#FFFFFF',
    }),
    ...(status === CandidatureStatut.Absent && {
      backgroundColor: '#F5F5F5',
      color: '#757575',
    }),
  },
}));

export default function CandidatureTableRow({
  row,
  selected,
  onSelectRow,
  handleEdit,
  handleView,
  columns,
  dense,
  activeTab,
  onStatusChange
}: CandidatureTableRowProps) {
  const [formModalOpen, setFormModalOpen] = useState(false);
  const [emailModalOpen, setEmailModalOpen] = useState(false);
  const [rdvDate, setRdvDate] = useState(row.dateHeureRdvAgence || '');
  const [rdvDateDayjs, setRdvDateDayjs] = useState(row.dateHeureRdvAgence ? dayjs(row.dateHeureRdvAgence) : null);
  const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
  const [contractStatus, setContractStatus] = useState(row.contrat || 'non signé');
  const theme = useTheme();

  const STATUS_OPTIONS = [
    { value: CandidatureStatut.ATraiter, label: 'À traiter' },
    { value: CandidatureStatut.EnCours, label: 'En cours' },
    { value: CandidatureStatut.Retenu, label: 'Retenu' },
    { value: CandidatureStatut.Valide, label: 'Validé' },
    { value: CandidatureStatut.Refuse, label: 'Refusé' },
    { value: CandidatureStatut.Blackliste, label: 'Blacklisté' },
    { value: CandidatureStatut.Absent, label: 'Absent' },
  ];
  const CONTRACT_OPTIONS = [
    { label: 'Signé', value:CandidatureContratStatut.Signe},
    { label: 'Non signé', value: CandidatureContratStatut.NonSigne }
  ];

  const getStatusColor = (status: CandidatureStatut) => {
    switch (status) {
      case CandidatureStatut.ATraiter:
        return 'warning';
      case CandidatureStatut.EnCours:
        return 'info';
      case CandidatureStatut.Retenu:
        return 'primary';
      case CandidatureStatut.Valide:
        return 'success';
      case CandidatureStatut.Refuse:
        return 'error';
      case CandidatureStatut.Blackliste:
        return 'error';
      case CandidatureStatut.Absent:
        return 'default';
      default:
        return 'default';
    }
  };

  const getStatusHexColor = (status: CandidatureStatut) => {
    switch (status) {
      case CandidatureStatut.ATraiter:
        return '#746CD4';
      case CandidatureStatut.EnCours:
        return '#0288d1';
      case CandidatureStatut.Retenu:
        return '#B78103';
      case CandidatureStatut.Valide:
        return '#36B37E';
      case CandidatureStatut.Refuse:
        return '#d32f2f';
      case CandidatureStatut.Blackliste:
        return '#2D2D2D';
      case CandidatureStatut.Absent:
        return '#757575';
      default:
        return '#757575';
    }
  };

  const getStatusLabel = (status: CandidatureStatut) => {
    switch (status) {
      case CandidatureStatut.ATraiter:
        return 'À traiter';
      case CandidatureStatut.EnCours:
        return 'En cours';
      case CandidatureStatut.Retenu:
        return 'Retenu';
      case CandidatureStatut.Valide:
        return 'Validé';
      case CandidatureStatut.Refuse:
        return 'Refusé';
      case CandidatureStatut.Blackliste:
        return 'Blacklisté';
      case CandidatureStatut.Absent:
        return 'Absent';
      default:
        return status;
    }
  };

  const handleSendForm = (formulaireId: string, observation: string) => {
    // Here you would implement the actual form sending logic
    console.log(`Sending form ${formulaireId} to ${row.nom} ${row.prenom} with observation: ${observation}`);

    // Example implementation - Update candidature status to "En cours" after sending form
    const updatedCandidature = {
      ...row,
      statut: CandidatureStatut.EnCours,
      lastFormulaireSent: formulaireId,
      lastFormulaireSentDate: new Date().toISOString(),
      lastObservation: observation
    };

    handleEdit(updatedCandidature);
  };

  const handleSendEmail = (subject: string, message: string) => {
    // Here you would implement the actual email sending logic
    console.log(`Sending email to ${row.email} with subject: ${subject}`);
    console.log(`Message: ${message}`);

    // Example implementation - Update candidature with email details
    const updatedCandidature = {
      ...row,
      lastEmailSent: subject,
      lastEmailSentDate: new Date().toISOString(),
      lastEmailMessage: message
    };

    handleEdit(updatedCandidature);
  };

  const handleRdvDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setRdvDate(e.target.value);
  };

  const handleDatePickerChange = (newValue: dayjs.Dayjs | null) => {
    if (newValue) {
      const formattedDate = newValue.format('YYYY-MM-DDTHH:mm');
      setRdvDate(formattedDate);
      setRdvDateDayjs(newValue);
    } else {
      setRdvDate('');
      setRdvDateDayjs(null);
    }
  };

  const handleClearDate = () => {
    setRdvDate('');
    setRdvDateDayjs(null);
  };

  const handleReplanifyRdv = () => {
    if (rdvDate) {
      const updatedCandidature = {
        ...row,
        dateHeureRdvAgence: rdvDate,
        statut: CandidatureStatut.Retenu // Change status back to Retenu
      };
      handleEdit(updatedCandidature);
    }
  };

  const handleStatusChange = (newStatus: CandidatureStatut) => {
    setIsStatusDialogOpen(true)
    const updatedCandidature = {
      ...row,
      statut: newStatus
    };
  };

  const handleContractStatusChange = (e: React.ChangeEvent<{ value: unknown }>) => {
    const newContractStatus = e.target.value as 'signé' | 'non signé';
    setContractStatus(newContractStatus);

    const updatedCandidature = {
      ...row,
      contrat: newContractStatus
    };

    handleEdit(updatedCandidature);
  };

  const handleDocumentDownload = () => {
    console.log('Download contract document for', row.nom, row.prenom);
  };

  // Create status options for the dialog
  const statusOptions: StatusOption[] = [
    { value: CandidatureStatut.ATraiter, label: 'À traiter' },
    { value: CandidatureStatut.EnCours, label: 'En cours' },
    { value: CandidatureStatut.Retenu, label: 'Retenu' },
    { value: CandidatureStatut.Valide, label: 'Validé' },
    { value: CandidatureStatut.Refuse, label: 'Refusé' },
    { value: CandidatureStatut.Blackliste, label: 'Blacklisté' },
    { value: CandidatureStatut.Absent, label: 'Absent' }
  ];

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

    // First ensure we have a renderable value for default case
    const getDefaultRenderable = (val: any): React.ReactNode => {
      if (val === null || val === undefined) return '-';
      if (val instanceof File) return val.name;
      if (typeof val === 'object') return JSON.stringify(val);
      return String(val);
    };

    switch (column.id) {
      case 'nom':
        return (
          <Stack direction="row" alignItems="center" spacing={2}>
            <Typography variant="body2" noWrap>
              {row.nom} {row.prenom}
            </Typography>
          </Stack>
        );

      case 'type':
        return (
          <Typography variant="body2" noWrap>
            {row.type ? row.type.replace('Candidature ', '') : 'Chauffeur'}
          </Typography>
        );

      case 'codePostal':
        return (
          <Typography variant="body2" noWrap>
            {row.codePostal}
          </Typography>
        );

      case 'ville':
        return (
          <Typography variant="body2" noWrap>
            {row.ville}
          </Typography>
        );

      case 'age':
        return (
          <Typography variant="body2" noWrap>
            {row.age}
          </Typography>
        );

      case 'email':
        return (
          <Typography variant="body2" noWrap>
            {row.email}
          </Typography>
        );

      case 'email_pro':
        // Only show email_pro if status is Valide
        if (row.statut === CandidatureStatut.Valide && row.email_pro) {
          return (
            <Typography variant="body2" noWrap>
              {row.email_pro}
            </Typography>
          );
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );

      case 'telephone':
        return (
          <Typography variant="body2" noWrap>
            {row.telephone}
          </Typography>
        );

      case 'statut':
        return (
          <StatusMenu
            value={row.statut}
            options={STATUS_OPTIONS}
            onChange={(newStatus) => onStatusChange(row, newStatus, 'statut' as keyof ICandidature)}
            chipComponent={(props) => <StyledChip status={props.value} {...props} />}
          />
        );

      case 'dateHeureRdvAgence':
        // Special handling for dateHeureRdvAgence in Absent RDV tab
        if (activeTab === CandidatureTab.AbsentRdv) {
          return (
            <Stack direction="row"  alignItems="center">
              <CustomDatePicker
                value={rdvDateDayjs}
                onChange={handleDatePickerChange}
                onClear={handleClearDate}
              />
              <ConditionalComponent isValid={!!rdvDate}>
              <CustomTooltip arrow  title="Replanifier RDV">
                <IconButton
                  color="primary"
                  onClick={handleReplanifyRdv}
                  size="small"
                  sx={ActionsIconButton}
                >
                  <FontAwesomeIcon icon={faCircleCheck} size="sm" />
                </IconButton>
              </CustomTooltip>
              </ConditionalComponent>

            </Stack>
          );
        } else if (row.dateHeureRdvAgence) {
          // Format the date for display
          const date = new Date(row.dateHeureRdvAgence);
          return date.toLocaleString('fr-FR', {
            year: 'numeric',
            month: 'numeric',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
          });
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );

        case 'contrat':
          if (row.statut === CandidatureStatut.Valide) {
            return (
              <StatusMenu
                value={row.contrat || 'non signé'}
                options={CONTRACT_OPTIONS}
                onChange={(newStatus) => onStatusChange(row, newStatus, 'contrat' as keyof ICandidature)}
                chipComponent={(props) => <StyledChip status={props.value} {...props} />}
              />
            );
          }
          return (
            <Typography variant="body2" color="text.secondary">
              -
            </Typography>
          );
      case 'document':
        return (
          <CustomTooltip arrow title="Télécharger les pièces jointes">
            <IconButton
              color="primary"
              onClick={handleDocumentDownload}
              size="small"
              sx={ActionsIconButton}
            >
              <FontAwesomeIcon icon={faFileLines} size="sm" />
            </IconButton>
          </CustomTooltip>
        );

      case 'raisonRefus':
        if (row.raisonRefus) {
          return (
            <Typography variant="body2" noWrap>
              {row.raisonRefus}
            </Typography>
          );
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );

      default:
        return (
          <Typography variant="body2" noWrap>
            {getDefaultRenderable(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>
          <Stack direction="row" spacing={1} justifyContent="center">
            <ConditionalComponent isValid={row.statut === CandidatureStatut.ATraiter}>
              <>
                <CustomTooltip arrow  title="Envoyer un formulaire">
                  <IconButton
                    color="primary"
                    onClick={(e) => {
                      e.stopPropagation();
                      setFormModalOpen(true);
                    }}
                    size="small"
                    sx={ActionsIconButton}
                  >
                    <FontAwesomeIcon icon={faPlus} size="sm" />
                  </IconButton>
                </CustomTooltip>
                <CustomTooltip arrow title="Envoyer un email">
                  <IconButton
                    color="primary"
                    onClick={(e) => {
                      e.stopPropagation();
                      setEmailModalOpen(true);
                    }}
                    size="small"
                    sx={ActionsIconButton}
                  >
                    <FontAwesomeIcon icon={faEnvelope} size="sm" />
                  </IconButton>
                </CustomTooltip>
              </>
            </ConditionalComponent>
            <TableActionColumn
              handleEdit={() => {
                handleEdit(row);
              }}
              tooltipTitles={{
                edit: 'Modifier',
                duplicate: 'Dupliquer',
                active: 'Actif',
                inactive: 'Inactif'
              }}
            />
          </Stack>
        </TableCell>
      </ContratStyledRow>

      <SendFormModal
        open={formModalOpen}
        onClose={() => setFormModalOpen(false)}
        candidature={row}
        onSend={handleSendForm}
      />

      <SendEmailModal
        open={emailModalOpen}
        onClose={() => setEmailModalOpen(false)}
        candidature={row}
        onSend={handleSendEmail}
      />

      <StatusChangeDialog
        open={isStatusDialogOpen}
        currentStatus={row.statut}
        statusOptions={statusOptions}
        onClose={() => setIsStatusDialogOpen(false)}
        onConfirm={handleStatusChange}
      />
    </>
  );
} 