"use client";

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  CircularProgress,
  Button
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { fetchGoodsReceiptStatusClient, type GoodsReceiptStatusRow } from '@/app/api/dashboard/client';

const REFRESH_MS = 15 * 60 * 1000;

const GoodsReceiptStatus: React.FC = () => {
  const { t } = useTranslation("dashboard");
  const [selectedDate, setSelectedDate] = useState<dayjs.Dayjs>(dayjs());
  const [data, setData] = useState<GoodsReceiptStatusRow[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [lastUpdated, setLastUpdated] = useState<dayjs.Dayjs | null>(null);
  const [screenCleared, setScreenCleared] = useState<boolean>(false);

  const loadData = useCallback(async () => {
    if (screenCleared) return;
    try {
      setLoading(true);
      const dateParam = selectedDate.format('YYYY-MM-DD');
      const result = await fetchGoodsReceiptStatusClient(dateParam);
      setData(result ?? []);
      setLastUpdated(dayjs());
    } catch (error) {
      console.error('Error fetching goods receipt status:', error);
      setData([]);
    } finally {
      setLoading(false);
    }
  }, [selectedDate, screenCleared]);

  useEffect(() => {
    if (screenCleared) return;
    loadData();
    
    const refreshInterval = setInterval(() => {
      loadData();
    }, REFRESH_MS);
    
    return () => clearInterval(refreshInterval);
  }, [loadData, screenCleared]);


  const selectedDateLabel = useMemo(() => {
    return selectedDate.format('YYYY-MM-DD');
  }, [selectedDate]);

  if (screenCleared) {
    return (
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Stack direction="row" spacing={2} justifyContent="space-between" alignItems="center">
            <Typography variant="body2" color="text.secondary">
              {t("Screen cleared")}
            </Typography>
            <Button variant="contained" onClick={() => setScreenCleared(false)}>
              {t("Restore Screen")}
            </Button>
          </Stack>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card sx={{ mb: 2 }}>
      <CardContent>
        {/* Header */}
        <Stack direction="row" spacing={2} sx={{ mb: 2 }} alignItems="center" flexWrap="wrap">
          <Stack direction="row" spacing={1} alignItems="center">
            <Typography variant="body2" sx={{ fontWeight: 600 }}>
              {t("Date")}:
            </Typography>
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <DatePicker
                value={selectedDate}
                onChange={(value) => {
                  if (!value) return;
                  setSelectedDate(value);
                }}
                slotProps={{
                  textField: {
                    size: "small",
                    sx: { minWidth: 160 }
                  }
                }}
              />
            </LocalizationProvider>
            <Typography variant="caption" color="text.secondary">
              {t("Allow to select Date to view history.")}
            </Typography>
          </Stack>

          <Box sx={{ flexGrow: 1 }} />

          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t("Auto-refresh every 15 minutes")} | {t("Last updated")}: {lastUpdated ? lastUpdated.format('HH:mm:ss') : '--:--:--'}
          </Typography>

          <Button variant="outlined" color="inherit" onClick={() => setScreenCleared(true)}>
            {t("Exit Screen")}
          </Button>
        </Stack>

        {/* Table */}
        <Box sx={{ mt: 2 }}>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
              <CircularProgress />
            </Box>
          ) : (
            <TableContainer component={Paper}>
              <Table size="small" sx={{ minWidth: 900 }}>
                <TableHead>
                  <TableRow sx={{ backgroundColor: 'grey.100' }}>
                    <TableCell sx={{ fontWeight: 600, width: '200px', padding: '8px 12px' }}>{t("Supplier")}</TableCell>
                    <TableCell sx={{ fontWeight: 600, width: '120px', padding: '8px 12px' }} align="center">{t("Expected No. of Delivery")}</TableCell>
                    <TableCell sx={{ fontWeight: 600, width: '150px', padding: '8px 12px' }} align="center">{t("No. of Orders Received at Dock")}</TableCell>
                    <TableCell sx={{ fontWeight: 600, width: '120px', padding: '8px 12px' }} align="center">{t("No. of Items Inspected")}</TableCell>
                    <TableCell sx={{ fontWeight: 600, width: '150px', padding: '8px 12px' }} align="center">{t("No. of Items with IQC Issue")}</TableCell>
                    <TableCell sx={{ fontWeight: 600, width: '180px', padding: '8px 12px' }} align="center">{t("No. of Items Completed Put Away at Store")}</TableCell>
                  </TableRow>
                  <TableRow sx={{ backgroundColor: 'grey.50' }}>
                    <TableCell sx={{ padding: '6px 12px' }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("Show Supplier Name")}
                      </Typography>
                    </TableCell>
                    <TableCell sx={{ padding: '6px 12px' }} align="center">
                      <Typography variant="caption" color="text.secondary">
                        {t("Based on Expected Delivery Date")}
                      </Typography>
                    </TableCell>
                    <TableCell sx={{ padding: '6px 12px' }} align="center">
                      <Typography variant="caption" color="text.secondary">
                        {t("Upon entry of DN and Lot No. for all items of the order")}
                      </Typography>
                    </TableCell>
                    <TableCell sx={{ padding: '6px 12px' }} align="center">
                      <Typography variant="caption" color="text.secondary">
                        {t("Upon any IQC decision received")}
                      </Typography>
                    </TableCell>
                    <TableCell sx={{ padding: '6px 12px' }} align="center">
                      <Typography variant="caption" color="text.secondary">
                        {t("Count any item with IQC defect in any IQC criteria")}
                      </Typography>
                    </TableCell>
                    <TableCell sx={{ padding: '6px 12px' }} align="center">
                      <Typography variant="caption" color="text.secondary">
                        {t("Upon completion of put away for an material in order. Count no. of items being put away")}
                      </Typography>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {data.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={6} align="center">
                        <Typography variant="body2" color="text.secondary">
                          {t("No data available")} ({selectedDateLabel})
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    data.map((row, index) => (
                      <TableRow 
                        key={`${row.supplierId ?? 'na'}-${index}`}
                        sx={{ 
                          '&:hover': { backgroundColor: 'grey.50' }
                        }}
                      >
                        <TableCell sx={{ padding: '8px 12px' }}>
                          {row.supplierName || '-'}
                        </TableCell>
                        <TableCell sx={{ padding: '8px 12px' }} align="center">
                          {row.expectedNoOfDelivery ?? 0}
                        </TableCell>
                        <TableCell sx={{ padding: '8px 12px' }} align="center">
                          {row.noOfOrdersReceivedAtDock ?? 0}
                        </TableCell>
                        <TableCell sx={{ padding: '8px 12px' }} align="center">
                          {row.noOfItemsInspected ?? 0}
                        </TableCell>
                        <TableCell sx={{ padding: '8px 12px' }} align="center">
                          {row.noOfItemsWithIqcIssue ?? 0}
                        </TableCell>
                        <TableCell sx={{ padding: '8px 12px' }} align="center">
                          {row.noOfItemsCompletedPutAwayAtStore ?? 0}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </Box>
      </CardContent>
    </Card>
  );
};

export default GoodsReceiptStatus;
