'use client'
import React, { useEffect, useState } from 'react';
import { Grid, InputAdornment, Button, Box, CircularProgress, Snackbar, Alert, LinearProgress, Typography, CardContent, DialogContent, DialogActions, Dialog, DialogContentText, DialogTitle, MenuItem } from '@mui/material';
import axios from 'axios';
import CustomFormLabel from '@/app/components/forms/theme-elements/CustomFormLabel';
import CustomTextField from '@/app/components/forms/theme-elements/CustomTextField';
import CustomOutlinedInput from '@/app/components/forms/theme-elements/CustomOutlinedInput';
import { getSession } from '@/utils/sessionData';
import PageContainer from '../components/container/PageContainer';
import Image from "next/image";
import { useRouter, useSearchParams } from 'next/navigation';

interface CassettePayload {
  cassett_id: number;
  value: number;
  count: number;
}

interface CassetteState {
  id?: number;
  cassett_id: number;
  value: string;
  count: string;
}

type SnackbarState = {
  open: boolean;
  severity: 'success' | 'error' | 'warning' | 'info';
  message: string;
};

export default function F53CassettesForm() {
  const [cassettes, setCassettes] = useState<CassetteState[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isSaving, setIsSaving] = useState<boolean>(false);
  const [snackbar, setSnackbar] = useState<SnackbarState>({ open: false, severity: 'success', message: '' });
  const searchParams = useSearchParams();
  const router = useRouter();
  const kioskId = searchParams?.get("kioskId") ?? searchParams?.get("kiosk_id");
  const [open, setOpen] = React.useState(false);
  const [selectedCassette, setSelectedCassette] = useState<CassetteState | null>(null);
  const [selectedCassetteIdx, setSelectedCassetteIdx] = useState<number | null>(null);

  const handleClickOpen = (c: CassetteState, idx: number) => {
    // open dialog with a deep copy so we don't mutate array until save
    setSelectedCassette({ ...c });
    setSelectedCassetteIdx(idx);
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
    setSelectedCassette(null);
    setSelectedCassetteIdx(null);
  };

  useEffect(() => {
    fetchCassettes();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchCassettes = async () => {
    try {
      setIsLoading(true);
      const session = getSession?.();
      const res = await axios.get(`https://kapi.logiclane.tech/api/kiosk/getF53Cassettes?kiosk_id=${kioskId}`, {
        headers: session?.token ? { Authorization: `Bearer ${session.token}` } : undefined,
      });

      if (res.data?.status === 'success' && Array.isArray(res.data.cassettes)) {
        setCassettes(
          res.data.cassettes.map((c: any) => ({
            id: c.id,
            cassett_id: Number(c.cassett_id),
            value: String(c.value ?? ''),
            count: String(c.count ?? ''),
          })) as CassetteState[]
        );
      } else {
        setSnackbar({ open: true, severity: 'warning', message: 'Unexpected response from server' });
      }
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error(err);
      setSnackbar({ open: true, severity: 'error', message: 'Failed to fetch cassettes' });
    } finally {
      setIsLoading(false);
    }
  };

  // keep this for inline edits if needed
  const handleChange = (index: number, field: keyof CassetteState, value: string) => {
    setCassettes(prev => {
      const copy = [...prev];
      copy[index] = { ...copy[index], [field]: value } as CassetteState;
      return copy;
    });
  };

  const handleDialogFieldChange = (field: keyof CassetteState, value: string) => {
    setSelectedCassette((prev): any => {
      if (!prev) return prev;

      if (field === 'count') {
        // Only allow digits for count
        const clean = value.replace(/[^0-9]/g, '');
        return { ...prev, [field]: clean };
      }

      if (field === 'value') {
        // Convert dropdown value to number
        return { ...prev, [field]: Number(value) };
      }

      return { ...prev, [field]: value };
    });
  };

  const buildPayload = (items: CassetteState[]): { cassettes: CassettePayload[] } => {
    return {
      cassettes: items.map(i => ({ cassett_id: Number(i.cassett_id), value: Number(i.value || 0), count: Number(i.count || 0) })),
    };
  };

  const saveAll = async () => {
    const payload = buildPayload(cassettes);
    try {
      setIsSaving(true);
      const session = getSession?.();
      // include kiosk_id as query param so backend knows which kiosk to target
      await axios.post(`https://kapi.logiclane.tech/api/kiosk/setF53Cassettes?kiosk_id=${kioskId}`, { ...payload, kiosk_id: kioskId }, {
        headers: session?.token ? { Authorization: `Bearer ${session.token}` } : undefined,
      });
      setSnackbar({ open: true, severity: 'success', message: 'Saved successfully' });
      await fetchCassettes();
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error(err);
      setSnackbar({ open: true, severity: 'error', message: 'Failed to save cassettes' });
    } finally {
      setIsSaving(false);
    }
  };

  // Save just one cassette — uses selectedCassette and kioskId
  const saveOne = async (index?: number | null) => {
    const idx = typeof index === 'number' ? index : selectedCassetteIdx;
    if (idx === null || idx === undefined) {
      setSnackbar({ open: true, severity: 'error', message: 'No cassette selected to save.' });
      return;
    }

    const c = selectedCassette ?? cassettes[idx];
    if (!c) {
      setSnackbar({ open: true, severity: 'error', message: 'Invalid cassette.' });
      return;
    }

    const payload = buildPayload([c]);

    try {
      setIsSaving(true);
      const session = getSession?.();
      await axios.post(`https://kapi.logiclane.tech/api/kiosk/setF53Cassettes?kiosk_id=${kioskId}`, { ...payload, kiosk_id: kioskId }, {
        headers: session?.token ? { Authorization: `Bearer ${session.token}` } : undefined,
      });

      // Update local state optimistically
      setCassettes(prev => {
        const copy = [...prev];
        copy[idx] = { ...copy[idx], value: String(payload.cassettes[0].value), count: String(payload.cassettes[0].count) };
        return copy;
      });

      setSnackbar({ open: true, severity: 'success', message: `Cassette ${c.cassett_id} saved` });
      // optionally refetch to ensure canonical data from server
      await fetchCassettes();
      handleClose();
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error(err);
      setSnackbar({ open: true, severity: 'error', message: `Failed to save cassette ${c.cassett_id}` });
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <Box display="flex" alignItems="center" justifyContent="center" p={4}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <PageContainer title="F53 Setup" description="this is F53 Setup">

      <div>
        <Typography fontSize={26} fontWeight={'bold'} marginBottom={5}>F53 Cassettes</Typography>

        <Grid container spacing={3}>
          {cassettes.map((c, idx) => (
            <Grid key={c.cassett_id}>
              <Box bgcolor={"primary.light"} textAlign="center"
                onClick={() => handleClickOpen(c, idx)} sx={{ cursor: 'pointer', borderRadius: 1 }}>
                <CardContent>
                  <Image src={'/images/svgs/icon-briefcase.svg'} alt={"/images/svgs/icon-briefcase.svg"} width="50" height="50" />
                  <Typography mt={1} variant="subtitle1" fontWeight={600}>
                    Cassette {c.cassett_id} - ${c.value}
                  </Typography>
                  <Typography variant="h5" mt={2} fontWeight={600}>
                    Bill count - {c.count}
                  </Typography>
                </CardContent>
              </Box>
            </Grid>
          ))}
        </Grid>

        <Dialog open={open} onClose={handleClose}>
          <DialogTitle>Cassette - {selectedCassette?.cassett_id}</DialogTitle>
          <DialogContent>
            <Box sx={{ mt: 2 }}>
              <CustomTextField
                select
                autoFocus
                margin="dense"
                id="value"
                label="Value ($)"
                value={selectedCassette?.value ?? ''}
                onChange={(e: any) => handleDialogFieldChange('value', e.target.value)}
                fullWidth
              >
                {[1, 2, 5, 10, 20, 50, 100].map((val) => (
                  <MenuItem key={val} value={val}>
                    {val}
                  </MenuItem>
                ))}
              </CustomTextField>
            </Box>
            <Box sx={{ mt: 2 }}>
              <CustomTextField
                margin="dense"
                id="count"
                label="Count"
                type="text"
                value={selectedCassette?.count ?? ''}
                onChange={(e: any) => handleDialogFieldChange('count', e.target.value)}
                fullWidth
              />
            </Box>
          </DialogContent>
          <DialogActions>
            <Button color="error" onClick={handleClose} disabled={isSaving}>
              Cancel
            </Button>
            <Button onClick={() => saveOne(selectedCassetteIdx)} disabled={isSaving}>
              {isSaving ? 'Saving...' : 'Update'}
            </Button>
          </DialogActions>
        </Dialog>

        <Snackbar open={snackbar.open} autoHideDuration={3000} onClose={() => setSnackbar(s => ({ ...s, open: false }))}>
          <Alert severity={snackbar.severity} onClose={() => setSnackbar(s => ({ ...s, open: false }))}>
            {snackbar.message}
          </Alert>
        </Snackbar>
      </div>
    </PageContainer>
  );
}
