import { useMemo, useState } from 'react';

// material-ui

import {
  Autocomplete,
  Avatar,
  Box,
  Button,
  Grid,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Stack,
  TextField,
  Typography,
  useMediaQuery,
  useTheme
} from '@mui/material';
import { MdDirectionsBike } from 'react-icons/md';
import { DT, tint } from 'themes/dt/tokens';
import { useMutation, useQuery } from '@tanstack/react-query';

// project import
import MainCard from 'components/MainCard';
import { createMiler, getHubs } from 'pages/api/doormileApi';
import { getTenants, fetchAppLocations } from 'pages/api/api';
import Loader from 'components/Loader';
import { enqueueSnackbar } from 'notistack';
import { useNavigate } from 'react-router';

const VEHICLE_TYPES = ['Bike', 'Scooter', 'Bicycle', 'Car', 'Van'];

const Createrider = () => {
  const [displayname, setDisplayname] = useState('');
  const [authname, setAuthname] = useState('');
  const [emailaddress, setEmailaddress] = useState('');
  const [mobilenumber, setMobilenumber] = useState('');
  const [password, setPassword] = useState('');
  const [vehicletype, setVehicletype] = useState('Bike');
  const [selectedTenant, setSelectedTenant] = useState(null);
  const [selectedHub, setSelectedHub] = useState(null);
  const [selectedLocation, setSelectedLocation] = useState(null);

  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));

  // Doormile staff (tenantid 0/null in the token) manage riders across every
  // tenant and must pick one; a client console login is scoped to its own
  // tenant server-side, so the picker is unnecessary there.
  const loginTenantId = localStorage.getItem('tenantid');
  const isDoormileStaff = !loginTenantId || loginTenantId === '0';

  const { data: tenants = [] } = useQuery({
    queryKey: ['createrider-tenants'],
    queryFn: getTenants,
    enabled: isDoormileStaff
  });

  const { data: hubs = [] } = useQuery({
    queryKey: ['createrider-hubs'],
    queryFn: getHubs
  });

  const { data: locations = [] } = useQuery({
    queryKey: ['createrider-locations'],
    queryFn: fetchAppLocations
  });

  const hubOptions = useMemo(() => hubs || [], [hubs]);
  const locationOptions = useMemo(() => (locations || []).filter((l) => l.applocationid), [locations]);

  const opentoast = (message) => {
    enqueueSnackbar(message, {
      variant: 'error',
      anchorOrigin: { vertical: 'top', horizontal: 'right' },
      autoHideDuration: 2000
    });
  };

  const createMilerMutation = useMutation({
    mutationFn: (payload) => createMiler(payload),
    onSuccess: (res) => {
      if (res.success) {
        enqueueSnackbar('Rider created successfully', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        navigate('/doormile/riders');
      } else {
        opentoast(res.message || 'Failed to create rider');
      }
    },
    onError: (err) => {
      opentoast(err.response?.data?.message || err.message || 'Failed to create rider');
    }
  });

  const createprofile = () => {
    const tenantid = isDoormileStaff ? selectedTenant?.tenantid : Number(loginTenantId);

    if (!displayname) {
      opentoast('Fill Display Name');
    } else if (!authname) {
      opentoast('Fill Login Name');
    } else if (!mobilenumber || mobilenumber.length !== 10) {
      opentoast('Fill a valid 10-digit Mobile Number');
    } else if (!emailaddress) {
      opentoast('Fill Email Address');
    } else if (!password) {
      opentoast('Fill Password');
    } else if (isDoormileStaff && !tenantid) {
      opentoast('Choose Tenant');
    } else if (!selectedLocation?.applocationid) {
      opentoast('Choose City');
    } else {
      // POST /admin/milers — configid defaults to 1001 server-side (the
      // miler-app login partition) and must not be overridden.
      const obj = {
        authname,
        displayname,
        email: emailaddress,
        contactno: mobilenumber,
        password,
        tenantid,
        defaultvehicletype: vehicletype,
        applocationid: selectedLocation?.applocationid,
        hubid: selectedHub?.hubid
      };

      createMilerMutation.mutate(obj);
    }
  };

  return (
    <>
      {createMilerMutation.isPending && <Loader />}

      <Box sx={{ p: { xs: 1.5, md: 3 } }}>
        <Grid item xs={12} sx={{ mb: 2 }}>
          <Paper
            sx={{
              p: 2.5,
              borderRadius: DT.radiusCard + 'px',
              boxShadow: DT.shadowSoft,
              border: '1px solid',
              borderColor: DT.borderSubtle,
              background: `linear-gradient(135deg, ${tint('#C01227')} 0%, ${tint('#D25463')} 100%)`
            }}
          >
            <Stack direction="row" spacing={1.5} alignItems="center">
              <Avatar sx={{ width: 48, height: 48, bgcolor: DT.brand }}>
                <MdDirectionsBike size={22} />
              </Avatar>
              <Typography variant="h3">Create Rider</Typography>
            </Stack>
          </Paper>
        </Grid>
        <MainCard sx={{ borderRadius: DT.radiusCard + 'px', boxShadow: DT.shadowSoft, borderColor: DT.borderSubtle }}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <MainCard sx={{ height: '100%' }}>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-display-name">Display Name</InputLabel>
                      <TextField
                        fullWidth
                        id="rider-display-name"
                        placeholder="e.g. Murali S"
                        onChange={(e) => setDisplayname(e.target.value)}
                        value={displayname}
                        autoComplete="off"
                      />
                    </Stack>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-auth-name">Login Name</InputLabel>
                      <TextField
                        fullWidth
                        id="rider-auth-name"
                        placeholder="Login name used on the miler app"
                        onChange={(e) => setAuthname(e.target.value)}
                        value={authname}
                        autoComplete="off"
                      />
                    </Stack>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-phone">Phone Number</InputLabel>
                      <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                        <Select defaultValue="+1" disabled sx={{ cursor: 'not-allowed' }}>
                          <MenuItem value="+1">+91</MenuItem>
                        </Select>
                        <TextField
                          type="number"
                          id="rider-phone"
                          fullWidth
                          placeholder="Phone Number"
                          onChange={(e) => {
                            if (e.target.value.toString().length <= 10) {
                              setMobilenumber(e.target.value);
                            }
                          }}
                          value={mobilenumber}
                          autoComplete="off"
                        />
                      </Stack>
                    </Stack>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-email">Email Address</InputLabel>
                      <TextField
                        type="email"
                        fullWidth
                        id="rider-email"
                        placeholder="Email Address"
                        onChange={(e) => setEmailaddress(e.target.value)}
                        value={emailaddress}
                        autoComplete="off"
                      />
                    </Stack>
                  </Grid>

                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-password">Password</InputLabel>
                      <TextField
                        type="password"
                        fullWidth
                        id="rider-password"
                        placeholder="Miler-app login password"
                        onChange={(e) => setPassword(e.target.value)}
                        value={password}
                        autoComplete="off"
                      />
                    </Stack>
                  </Grid>

                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-vehicle-type">Vehicle Type</InputLabel>
                      <Select id="rider-vehicle-type" fullWidth value={vehicletype} onChange={(e) => setVehicletype(e.target.value)}>
                        {VEHICLE_TYPES.map((v) => (
                          <MenuItem key={v} value={v}>
                            {v}
                          </MenuItem>
                        ))}
                      </Select>
                    </Stack>
                  </Grid>

                  {isDoormileStaff && (
                    <Grid item xs={12} sm={6}>
                      <Stack spacing={1.25}>
                        <InputLabel htmlFor="rider-tenant">Tenant</InputLabel>
                        <Autocomplete
                          id="rider-tenant"
                          options={tenants || []}
                          getOptionLabel={(option) => option.tenantname || ''}
                          value={selectedTenant}
                          onChange={(e, value) => setSelectedTenant(value)}
                          renderInput={(params) => <TextField {...params} placeholder="Choose tenant" />}
                        />
                      </Stack>
                    </Grid>
                  )}

                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-location">City</InputLabel>
                      <Autocomplete
                        id="rider-location"
                        options={locationOptions}
                        getOptionLabel={(option) => option.locationname || ''}
                        value={selectedLocation}
                        onChange={(e, value) => setSelectedLocation(value)}
                        renderInput={(params) => <TextField {...params} placeholder="Choose city" />}
                      />
                    </Stack>
                  </Grid>

                  <Grid item xs={12} sm={6}>
                    <Stack spacing={1.25}>
                      <InputLabel htmlFor="rider-hub">Hub (optional)</InputLabel>
                      <Autocomplete
                        id="rider-hub"
                        options={hubOptions}
                        getOptionLabel={(option) => option.hubname || ''}
                        value={selectedHub}
                        onChange={(e, value) => setSelectedHub(value)}
                        renderInput={(params) => <TextField {...params} placeholder="Choose hub (visibility on hub console)" />}
                      />
                    </Stack>
                  </Grid>
                </Grid>
              </MainCard>
            </Grid>
            <Grid item xs={12}>
              <Stack
                direction={{ xs: 'column', sm: 'row' }}
                justifyContent="flex-end"
                alignItems={{ xs: 'stretch', sm: 'center' }}
                spacing={2}
              >
                <Button variant="contained" onClick={createprofile} fullWidth={isMobile}>
                  Create
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </MainCard>
      </Box>
    </>
  );
};

export default Createrider;
