// @mui
import { Box, Stepper, Step, StepLabel, Card, Typography, Divider, Stack } from '@mui/material';
// React
import { useContext, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
// axios
import axios from '../../utils/axios';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import { fDate, fPostFormat } from '../../utils/formatTime';
import Iconify from '../../components/Iconify';

const steps = ['Review', 'Approval', 'Disbursement'];

interface DataHistoriesClaimRequest {
  title: string;
  description: string;
  created_at: string;
}

interface DataFilesClaimRequest {
  id: number;
  fileName: string;
  fileUrl: string;
}

interface DataClaimRequest {
  claimId: number;
  claimRequestId: number;
  fullName: string;
  histories: DataHistoriesClaimRequest[];
  status: string;
  submissionDate: string | Date;
  files: {
    claimConditions: DataFilesClaimRequest[];
    claimResults: DataFilesClaimRequest[];
    claimDiagnosis: DataFilesClaimRequest[];
  };
}

const DialogDetailClaim = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { corporateValue } = useContext(UserCurrentCorporateContext);
  const [corporateValueBefore, setCorporateValueBefore] = useState(corporateValue);
  const [data, setData] = useState<DataClaimRequest | null>(null);

  // inisialisasi pertama
  useEffect(() => {
    axios
      .get(`${corporateValue}/claim-report/${id}`)
      .then((response) => {
        setData(response.data.data);
      })
      .catch((error) => {
        console.error('Terjadi kesalahan:', error);
      });
  }, []);

  // Navigasi ke claim-report ketika corporateValue berubah
  useEffect(() => {
    if (corporateValueBefore !== corporateValue) {
      navigate(`/claim-report`);
    }
  }, [corporateValue]);

  return (
    <>
      <Stack
        alignItems="center"
        justifyContent="space-between"
        direction="row"
        sx={{ marginTop: 1 }}
      >
        <Typography variant="subtitle1" sx={{ height: 'max-content' }}>
          Claim Request for {data?.fullName}
        </Typography>
        <Stack>
          <Typography variant="caption">Submission date</Typography>
          <Typography variant="caption">
            {fPostFormat(data ? data.submissionDate : new Date(), 'dd / MM / yyyy')}
          </Typography>
        </Stack>
      </Stack>
      <Box sx={{ width: '100%', marginTop: 2 }}>
        <Stepper
          activeStep={data?.status === 'approved' ? 1 : data?.status === 'requested' ? 0 : 2}
          alternativeLabel
        >
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel>{label}</StepLabel>
            </Step>
          ))}
        </Stepper>
      </Box>
      <Stack marginTop={2}>
        <Typography variant="subtitle1" paddingY={2}>
          {fDate(data ? data?.histories[0].created_at : new Date())}
        </Typography>
      </Stack>
      <Stack direction="row" spacing={2}>
        <Divider orientation="vertical" flexItem sx={{ borderStyle: 'dashed' }} />
        <Stack spacing={2} sx={{ flex: 1, maxWidth: '100%' }}>
          {data?.histories.map((history, index) => (
            <Card sx={{ paddingY: 2, paddingX: 3 }} key={`${history.title}-${index}`}>
              <Stack direction="row" justifyContent="space-between" alignItems="center">
                <Typography variant="body1">
                  {fPostFormat(history.created_at, 'HH:mm')} WIB
                </Typography>
              </Stack>
              <Divider sx={{ marginY: 2 }} />
              <Stack>
                <Typography variant="subtitle2" color="#404040">
                  Details : {history.description}
                </Typography>
                <Typography
                  variant="caption"
                  color="#757575"
                  sx={{ marginTop: 2, marginBottom: 1 }}
                >
                  {history.title}
                </Typography>
              </Stack>
            </Card>
          ))}
          <Card sx={{ paddingY: 2, paddingX: 3 }}>
            <Stack direction="row" justifyContent="space-between" alignItems="center">
              <Typography variant="body1" fontWeight={600}>
                <Iconify icon="eva:file-text-fill" /> Dokumen Kelengkapan
              </Typography>
            </Stack>
            <Divider sx={{ marginY: 2 }} />

            <Typography fontWeight="600">Kondisi</Typography>
            <Stack>
              <Stack
                divider={<Divider orientation="horizontal" flexItem />}
                spacing={1}
                sx={{ marginY: 2 }}
              >
                {data &&
                  data.files.claimConditions.map((file, index) => (
                    <Stack direction="row" justifyContent={'space-between'} key={index}>
                      <a
                        href={file.fileUrl}
                        target="_blank"
                        style={{ textDecoration: 'none' }}
                        rel="noreferrer"
                      >
                        <Typography sx={{ color: 'text.secondary' }} variant="subtitle2">
                          - {file.fileName}
                        </Typography>
                      </a>
                    </Stack>
                  ))}
              </Stack>

              <Typography fontWeight="600">Diagnosa</Typography>
              <Stack
                divider={<Divider orientation="horizontal" flexItem />}
                spacing={1}
                sx={{ marginY: 2 }}
              >
                {data &&
                  data.files.claimDiagnosis.map((file, index) => (
                    <Stack direction="row" justifyContent={'space-between'} key={index}>
                      <a
                        href={file.fileUrl}
                        target="_blank"
                        style={{ textDecoration: 'none' }}
                        rel="noreferrer"
                      >
                        <Typography sx={{ color: 'text.secondary' }} variant="subtitle2">
                          - {file.fileName}
                        </Typography>
                      </a>
                    </Stack>
                  ))}
              </Stack>

              <Typography fontWeight="600">Hasil</Typography>
              <Stack
                divider={<Divider orientation="horizontal" flexItem />}
                spacing={1}
                sx={{ marginY: 2 }}
              >
                {data &&
                  data.files.claimResults.map((file, index) => (
                    <Stack direction="row" justifyContent={'space-between'} key={index}>
                      <a
                        href={file.fileUrl}
                        target="_blank"
                        style={{ textDecoration: 'none' }}
                        rel="noreferrer"
                      >
                        <Typography sx={{ color: 'text.secondary' }} variant="subtitle2">
                          - {file.fileName}
                        </Typography>
                      </a>
                    </Stack>
                  ))}
              </Stack>
            </Stack>
          </Card>
        </Stack>
      </Stack>
    </>
  );
};

export default DialogDetailClaim;
