import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from '@emotion/styled';
import {
  Button,
  TextField,
  FormControl,
  FormLabel,
  Box,
  Stack,
} from '@mui/material';
import Modal from './Modal/Modal';
import { TasksApi } from '../../api/tasks';
import { FormsApi } from '../../api/forms';
import { toast } from 'react-toastify';
import {
  CheckBoxCheckSvg,
  CheckBoxUncheckSvg,
  DateIcon,
  Edit,
  ExportSvg,
  TableIcon,
  UserIcon,
} from './icons/icons';
import { formatDate } from '../../utils/formatDate';
import { IconWithContent } from './IconWithContent';
import { Chip } from '../styles/StyledChip';
import { ExportButton } from '../common/Buttons/ButtonsActions';
import { FORM_TYPE_TRANSLATE } from '../../constants/constants';

const TaskCard = styled.div`
  width: 26.8rem;
  height: 15rem;
  display: flex;
  padding: 1.25rem;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  box-sizing: border-box;
  border: 0.06rem solid var(--Stroke, rgba(0, 0, 0, 0.1));
  border-radius: 1rem;
  box-shadow:
    0rem 2rem 4rem -2rem rgba(0, 0, 0, 0.02),
    0rem 4rem 6rem -1rem rgba(0, 0, 0, 0.02);
  background: var(--White, rgba(255, 255, 255, 1));
  overflow: hidden;
  cursor: pointer;
  position: relative;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
  }
`;

const CardHeader = styled.div`
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const TaskId = styled.div`
  font-size: 0.75rem;
  font-weight: 400;
  line-height: 1rem;
  letter-spacing: 0rem;
  text-align: left;
`;

const CardBody = styled.div`
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.8125rem;
  justify-content: flex-end;
  height: 100%;
`;

const TaskTitle = styled.div`
  font-size: 1rem;
  font-weight: 500;
  color: var(--Text-Primary, #333);
  line-height: 1.63;
  margin: 0;
  padding: 0;
`;

export const TaskCardComponent = ({
  taskForm,
  isForm = false,
  exportMode = false,
  isLoadingFile = false,
  onAddForExport,
  onExportClick,
}) => {
  const navigate = useNavigate();
  const { id, title, org_unit, form_type_code, year } = taskForm;

  const [isEditModalOpen, setEditModalOpen] = useState(false);
  const [editedTitle, setEditedTitle] = useState('');
  const [currentTitle, setCurrentTitle] = useState(FORM_TYPE_TRANSLATE[form_type_code] ||'');
  const [isChecked, setIsChecked] = useState(false);

  useEffect(() => {
    setIsChecked(false);
  }, [exportMode]);

  const handleOpenEdit = (event) => {
    event.stopPropagation();
    setEditedTitle(currentTitle);
    setEditModalOpen(true);
  };

  const handleCloseEdit = () => {
    setEditModalOpen(false);
  };

  const handleCheckboxClick = (event) => {
    event.stopPropagation();
    if (!isLoadingFile) {
      setIsChecked(!isChecked);
      onAddForExport(!isChecked);
    } else {
      toast.warning('Файл формируется!');
    }
  };

  const handleExportTask = (event) => {
    event.stopPropagation();
    onExportClick?.(id, title);
  };

  const updateTask = async (nextTitle) => {
    try {
      await TasksApi.editTask(id, { title: nextTitle });
      setCurrentTitle(nextTitle);
      setEditModalOpen(false);
      toast.success('Название задачи обновлено');
    } catch (error) {
      toast.error(
        error?.response?.data?.detail || 'Не удалось обновить название задачи',
      );
    }
  };

  const updateForm = async (nextTitle) => {
    try {
      await FormsApi.updateForm(id, { title: nextTitle });
      setCurrentTitle(nextTitle);
      setEditModalOpen(false);
    } catch (error) {
      toast.error(
        error?.response?.data?.detail || 'Не удалось обновить название формы',
      );
    }
  };

  const handleSaveTitle = async () => {
    const nextTitle = editedTitle.trim();
    if (!nextTitle) {
      toast.error('Название не может быть пустым');
      return;
    }
    if (nextTitle === currentTitle) {
      setEditModalOpen(false);
      return;
    }

    if (isForm) {
      await updateForm(nextTitle);
      return;
    }

    await updateTask(nextTitle);
  };

  return (
    <>
      <TaskCard
        onClick={(event) => {
          if (exportMode) {
            handleCheckboxClick(event);
          } else {
            navigate(`/${isForm ? 'form' : 'task'}/${id}`);
          }
        }}
        key={id}
      >
        <Box sx={{ width: "100%" }}>
          <CardHeader>
            <TaskId>ID: {id}</TaskId>
            {/* TODO: вернется, когда будут реализованы статусы на бэке */}
            {/* <StatusBadge status={status} />  */}
            <Stack direction={'row'} spacing={'.5rem'}>
              {!isForm && !exportMode && (
                <ExportButton onClick={handleExportTask} />
              )}
              {/* <Edit onClick={handleOpenEdit} /> */}
            </Stack>
          </CardHeader>

          <TaskTitle>{currentTitle}</TaskTitle>
        </Box>

        <Stack
        sx={{
 direction:'row',
          justifyContent:'space-between',
          width:'100%',
          alignItems:'end',
        }}
         
        >

          <CardBody>
            <IconWithContent icon={<DateIcon />}>{year}</IconWithContent>
            <IconWithContent icon={<UserIcon />}>
              <Chip>{org_unit.title}</Chip>
            </IconWithContent>
            {/* <IconWithContent icon={<TableIcon />}>
              Таблиц: {tables_count}
            </IconWithContent> */}
          </CardBody>

          {exportMode && (
            <div>
              {isChecked ? (
                <CheckBoxCheckSvg size="1.625rem" />
              ) : (
                <CheckBoxUncheckSvg size="1.625rem" />
              )}
            </div>
          )}
        </Stack>
      </TaskCard>

      <Modal
        open={isEditModalOpen}
        onClose={handleCloseEdit}
        title={isForm ? 'Редактировать форму' : 'Редактировать задачу'}
        actions={
          <>
            <Button variant="grey" onClick={handleCloseEdit}>
              Отменить
            </Button>
            <Button variant="contained" onClick={handleSaveTitle}>
              Сохранить
            </Button>
          </>
        }
      >
        <div className="flex flex-col gap-4">
          <FormControl fullWidth>
            <FormLabel required>
              {isForm ? 'Название формы' : 'Название задачи'}
            </FormLabel>
            <TextField
              size="small"
              placeholder={
                isForm ? 'Укажите название формы' : 'Укажите название задачи'
              }
              value={editedTitle}
              onChange={(e) => setEditedTitle(e.target.value)}
              autoFocus
            />
          </FormControl>
        </div>
      </Modal>
    </>
  );
};
