import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Grid, Stack, Button, IconButton, Typography, Box, TextField, MenuItem, Chip,
  Table, TableBody, TableCell, TableContainer, TableHead, TableRow
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import AutorenewIcon from '@mui/icons-material/Autorenew';
import Inventory2OutlinedIcon from '@mui/icons-material/Inventory2Outlined';
import TwoWheelerOutlinedIcon from '@mui/icons-material/TwoWheelerOutlined';
import MapOutlinedIcon from '@mui/icons-material/MapOutlined';
import RouteOutlinedIcon from '@mui/icons-material/RouteOutlined';
import PersonAddAltOutlinedIcon from '@mui/icons-material/PersonAddAltOutlined';

import PageHeader from '@/components/PageHeader';
import StatCard from '@/components/StatCard';
import MainCard from '@/components/MainCard';
import StatusChip from '@/components/StatusChip';
import UserAvatar from '@/components/UserAvatar';
import { orders, riders } from '@/data/mock';
import { inr } from '@/utils/format';

const ZONES = ['Zone A', 'Zone B', 'Zone C', 'Zone D'];
const PROFIT = [42, 58, 36, 50, 28, 64];

// derive assignment rows from orders + riders mock
const ROWS = orders.slice(0, 6).map((o, i) => ({
  ...o,
  zone: ZONES[i % ZONES.length],
  rider: riders[i % riders.length].name,
  profit: PROFIT[i % PROFIT.length]
}));

export default function AssignOrders() {
  const navigate = useNavigate();
  const [payment, setPayment] = useState('all');
  const [rider, setRider] = useState('auto');

  return (
    <>
      <PageHeader
        title={
          <Stack direction="row" spacing={1.5} alignItems="center">
            <IconButton onClick={() => navigate('/orders')} size="small"><ArrowBackIcon /></IconButton>
            <span>Assign Orders</span>
          </Stack>
        }
        breadcrumbs={[{ label: 'Orders', to: '/orders' }, { label: 'Assign Orders' }]}
        action={
          <Button variant="outlined" startIcon={<AutorenewIcon />}>Re-Assign</Button>
        }
      />

      <Grid container spacing={2.5} sx={{ mb: 1 }}>
        <Grid item xs={12} sm={6} lg={3}><StatCard title="Orders" value={8} icon={Inventory2OutlinedIcon} caption="To assign" /></Grid>
        <Grid item xs={12} sm={6} lg={3}><StatCard title="Riders" value={5} icon={TwoWheelerOutlinedIcon} color="info" caption="Available" /></Grid>
        <Grid item xs={12} sm={6} lg={3}><StatCard title="Zones" value={4} icon={MapOutlinedIcon} color="warning" caption="Covered" /></Grid>
        <Grid item xs={12} sm={6} lg={3}><StatCard title="Kilometer" value={64} icon={RouteOutlinedIcon} color="success" caption="Total route" /></Grid>
      </Grid>

      <MainCard title="Assignment Plan" noPadding sx={{ mt: 1.5 }}>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>#</TableCell>
                <TableCell>Zone</TableCell>
                <TableCell>Tenant</TableCell>
                <TableCell>Order Location</TableCell>
                <TableCell>Pickup</TableCell>
                <TableCell>Delivery</TableCell>
                <TableCell>Notes</TableCell>
                <TableCell>Rider</TableCell>
                <TableCell>Type</TableCell>
                <TableCell align="right">Profit</TableCell>
                <TableCell align="right">Charges</TableCell>
                <TableCell align="right">KMS</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {ROWS.map((r) => (
                <TableRow key={r.id} hover>
                  <TableCell sx={{ fontWeight: 600, color: 'primary.main' }}>{r.id}</TableCell>
                  <TableCell>
                    <Chip size="small" label={r.zone} sx={{ bgcolor: 'primary.lighter', color: 'primary.dark', fontWeight: 600 }} />
                  </TableCell>
                  <TableCell>{r.tenant}</TableCell>
                  <TableCell>{r.location}</TableCell>
                  <TableCell>{r.pickup}</TableCell>
                  <TableCell>{r.drop}</TableCell>
                  <TableCell><Typography variant="caption" color="text.secondary" noWrap>{r.notes || '—'}</Typography></TableCell>
                  <TableCell>
                    <Stack direction="row" spacing={1} alignItems="center">
                      <UserAvatar name={r.rider} size={28} />
                      <Typography variant="body2">{r.rider}</Typography>
                    </Stack>
                  </TableCell>
                  <TableCell><StatusChip status={r.payment} /></TableCell>
                  <TableCell align="right" sx={{ color: 'success.main', fontWeight: 600 }}>{inr(r.profit)}</TableCell>
                  <TableCell align="right" sx={{ fontWeight: 600 }}>{inr(r.charges)}</TableCell>
                  <TableCell align="right">{r.kms}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </MainCard>

      <Box sx={{ mt: 2.5 }}>
        <Grid container spacing={2.5} alignItems="center">
          <Grid item xs={12} sm={6} md={3}>
            <TextField select fullWidth size="small" label="Choose Payment" value={payment} onChange={(e) => setPayment(e.target.value)}>
              <MenuItem value="all">All Payments</MenuItem>
              <MenuItem value="prepaid">Prepaid</MenuItem>
              <MenuItem value="cod">COD</MenuItem>
            </TextField>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <TextField select fullWidth size="small" label="Choose Rider" value={rider} onChange={(e) => setRider(e.target.value)}>
              <MenuItem value="auto">Auto Assign</MenuItem>
              {riders.map((rd) => <MenuItem key={rd.id} value={rd.id}>{rd.name}</MenuItem>)}
            </TextField>
          </Grid>
        </Grid>
      </Box>

      <Stack direction="row" spacing={1.5} justifyContent="flex-end" sx={{ mt: 2.5 }}>
        <Button variant="outlined" startIcon={<ArrowBackIcon />} onClick={() => navigate('/orders')}>Back</Button>
        <Button variant="contained" startIcon={<PersonAddAltOutlinedIcon />} onClick={() => navigate('/orders')}>
          Assign Orders
        </Button>
      </Stack>
    </>
  );
}
