import React, { useState } from 'react';
import {
  Avatar,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  InputLabel,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography
} from '@mui/material';
import { MdRadar, MdAdd, MdEdit, MdDeleteOutline } from 'react-icons/md';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import Loader from 'components/Loader';
import PageHeader from 'components/nearle_components/PageHeader';
import {
  getCompetitorBranches,
  createCompetitorBranch,
  updateCompetitorBranch,
  deleteCompetitorBranch,
  getCarrierPricing,
  createCarrierPricing,
  updateCarrierPricing,
  deleteCarrierPricing
} from 'pages/api/doormileApi';
import { enqueueSnackbar } from 'notistack';

// ============================================================================
// Neither /admin/competitor-branches nor /admin/carrier-pricing document a
// request/response body anywhere — express-console-api.md lists only the
// routes. The fields below (branchname/city/address for branches,
// carriername/vehicletype/baseprice/priceperkm for pricing) are a best-effort
// guess following the naming conventions used elsewhere in this API and are
// UNVERIFIED — expect the create/edit calls here to need correction once a
// real request/response has been seen.
// ============================================================================

const DT = {
  radiusCard: 14,
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surfaceAlt: '#f8fafc'
};
const a = (c, suffix) => `${c}${suffix}`;
const soft = (c) => a(c, '18');
const BRAND = '#C01227';

const TABS = [
  { key: 'branches', label: 'Competitor Branches' },
  { key: 'pricing', label: 'Carrier Pricing' }
];

const emptyBranch = { id: null, branchname: '', competitorname: '', city: '', address: '' };
const emptyCarrier = { id: null, carriername: '', vehicletype: '', baseprice: '', priceperkm: '' };

const CompetitiveIntel = () => {
  const queryClient = useQueryClient();
  const [tab, setTab] = useState('branches');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [branchForm, setBranchForm] = useState(emptyBranch);
  const [carrierForm, setCarrierForm] = useState(emptyCarrier);

  const { data: branches = [], isLoading: branchesLoading } = useQuery({
    queryKey: ['competitor-branches'],
    queryFn: getCompetitorBranches
  });
  const { data: carrierPricing = [], isLoading: carrierLoading } = useQuery({
    queryKey: ['carrier-pricing'],
    queryFn: getCarrierPricing
  });

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

  const branchMutation = useMutation({
    mutationFn: (payload) => (payload.id ? updateCompetitorBranch(payload.id, payload.data) : createCompetitorBranch(payload.data)),
    onSuccess: (res) => {
      if (res.success) {
        opentoast(branchForm.id ? 'Branch updated' : 'Branch created', 'success');
        queryClient.invalidateQueries({ queryKey: ['competitor-branches'] });
        setDialogOpen(false);
      } else {
        opentoast(res.message || 'Failed to save branch');
      }
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to save branch')
  });

  const branchDeleteMutation = useMutation({
    mutationFn: (id) => deleteCompetitorBranch(id),
    onSuccess: (res) => {
      if (res.success) {
        opentoast('Branch deleted', 'success');
        queryClient.invalidateQueries({ queryKey: ['competitor-branches'] });
      } else opentoast(res.message || 'Failed to delete branch');
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to delete branch')
  });

  const carrierMutation = useMutation({
    mutationFn: (payload) => (payload.id ? updateCarrierPricing(payload.id, payload.data) : createCarrierPricing(payload.data)),
    onSuccess: (res) => {
      if (res.success) {
        opentoast(carrierForm.id ? 'Carrier pricing updated' : 'Carrier pricing created', 'success');
        queryClient.invalidateQueries({ queryKey: ['carrier-pricing'] });
        setDialogOpen(false);
      } else {
        opentoast(res.message || 'Failed to save carrier pricing');
      }
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to save carrier pricing')
  });

  const carrierDeleteMutation = useMutation({
    mutationFn: (id) => deleteCarrierPricing(id),
    onSuccess: (res) => {
      if (res.success) {
        opentoast('Carrier pricing deleted', 'success');
        queryClient.invalidateQueries({ queryKey: ['carrier-pricing'] });
      } else opentoast(res.message || 'Failed to delete carrier pricing');
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to delete carrier pricing')
  });

  const idOf = (row) => row.id ?? row.competitorbranchid ?? row.carrierpricingid;

  const openCreate = () => {
    if (tab === 'branches') setBranchForm(emptyBranch);
    else setCarrierForm(emptyCarrier);
    setDialogOpen(true);
  };

  const openEdit = (row) => {
    if (tab === 'branches') {
      setBranchForm({
        id: idOf(row),
        branchname: row.branchname || '',
        competitorname: row.competitorname || '',
        city: row.city || '',
        address: row.address || ''
      });
    } else {
      setCarrierForm({
        id: idOf(row),
        carriername: row.carriername || '',
        vehicletype: row.vehicletype || '',
        baseprice: row.baseprice ?? '',
        priceperkm: row.priceperkm ?? ''
      });
    }
    setDialogOpen(true);
  };

  const handleDelete = (row) => {
    if (!window.confirm('Delete this record?')) return;
    if (tab === 'branches') branchDeleteMutation.mutate(idOf(row));
    else carrierDeleteMutation.mutate(idOf(row));
  };

  const handleSave = () => {
    if (tab === 'branches') {
      if (!branchForm.branchname) {
        opentoast('Fill Branch Name');
        return;
      }
      const { id, ...data } = branchForm;
      branchMutation.mutate({ id, data });
    } else {
      if (!carrierForm.carriername || !carrierForm.baseprice) {
        opentoast('Fill Carrier Name and Base Price');
        return;
      }
      const { id, ...data } = carrierForm;
      carrierMutation.mutate({ id, data: { ...data, baseprice: Number(data.baseprice) || 0, priceperkm: Number(data.priceperkm) || 0 } });
    }
  };

  const rows = tab === 'branches' ? branches : carrierPricing;
  const isLoading = tab === 'branches' ? branchesLoading : carrierLoading;

  return (
    <>
      {(isLoading || branchMutation.isPending || carrierMutation.isPending) && <Loader />}

      <PageHeader
        title="Competitive Intel"
        subtitle="Live · Market Benchmarking"
        live
        action={
          <Button variant="contained" startIcon={<MdAdd size={16} />} onClick={openCreate} sx={{ bgcolor: BRAND, whiteSpace: 'nowrap' }}>
            {tab === 'branches' ? 'New Branch' : 'New Carrier Rate'}
          </Button>
        }
      />

      <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
        {TABS.map((t) => (
          <Box
            key={t.key}
            onClick={() => setTab(t.key)}
            sx={{
              px: 2,
              py: 0.75,
              borderRadius: 999,
              cursor: 'pointer',
              fontWeight: 700,
              fontSize: 13,
              bgcolor: tab === t.key ? BRAND : soft(BRAND),
              color: tab === t.key ? '#fff' : BRAND,
              border: `1px solid ${tab === t.key ? BRAND : soft(BRAND)}`
            }}
          >
            {t.label}
          </Box>
        ))}
      </Stack>

      <Paper elevation={0} sx={{ border: '1px solid', borderColor: DT.borderSubtle, borderRadius: DT.radiusCard / 8 + 'px', overflow: 'hidden', background: '#fff' }}>
        <TableContainer sx={{ maxHeight: 'calc(100vh - 260px)' }}>
          <Table stickyHeader sx={{ minWidth: 720 }}>
            <TableHead>
              {tab === 'branches' ? (
                <TableRow sx={{ '& th': { backgroundColor: DT.surfaceAlt, color: DT.textSecondary, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', borderBottom: `1px solid ${DT.borderSubtle}` } }}>
                  <TableCell>#</TableCell>
                  <TableCell>Branch Name</TableCell>
                  <TableCell>Competitor</TableCell>
                  <TableCell>City</TableCell>
                  <TableCell>Address</TableCell>
                  <TableCell align="right">Actions</TableCell>
                </TableRow>
              ) : (
                <TableRow sx={{ '& th': { backgroundColor: DT.surfaceAlt, color: DT.textSecondary, fontSize: 11, fontWeight: 800, textTransform: 'uppercase', borderBottom: `1px solid ${DT.borderSubtle}` } }}>
                  <TableCell>#</TableCell>
                  <TableCell>Carrier</TableCell>
                  <TableCell>Vehicle Type</TableCell>
                  <TableCell align="center">Base Price</TableCell>
                  <TableCell align="center">Price/Km</TableCell>
                  <TableCell align="right">Actions</TableCell>
                </TableRow>
              )}
            </TableHead>
            <TableBody>
              {rows.length === 0 && !isLoading ? (
                <TableRow>
                  <TableCell colSpan={6} sx={{ py: 6 }}>
                    <Stack alignItems="center" spacing={1.5}>
                      <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                        <MdRadar size={28} />
                      </Avatar>
                      <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                        No records to show
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                rows.map((row, index) => (
                  <TableRow key={idOf(row) || index} sx={{ '& td': { borderBottom: `1px solid ${DT.divider}` }, '&:hover': { backgroundColor: DT.surfaceAlt } }}>
                    <TableCell>{index + 1}</TableCell>
                    {tab === 'branches' ? (
                      <>
                        <TableCell>{row.branchname || '—'}</TableCell>
                        <TableCell>{row.competitorname || '—'}</TableCell>
                        <TableCell>{row.city || '—'}</TableCell>
                        <TableCell>{row.address || '—'}</TableCell>
                      </>
                    ) : (
                      <>
                        <TableCell>{row.carriername || '—'}</TableCell>
                        <TableCell>{row.vehicletype || '—'}</TableCell>
                        <TableCell align="center">{row.baseprice ?? '—'}</TableCell>
                        <TableCell align="center">{row.priceperkm ?? '—'}</TableCell>
                      </>
                    )}
                    <TableCell align="right">
                      <Stack direction="row" spacing={0.5} justifyContent="flex-end">
                        <Tooltip title="Edit">
                          <IconButton size="small" onClick={() => openEdit(row)} sx={{ color: BRAND }}>
                            <MdEdit size={16} />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Delete">
                          <IconButton size="small" onClick={() => handleDelete(row)} sx={{ color: '#ef4444' }}>
                            <MdDeleteOutline size={16} />
                          </IconButton>
                        </Tooltip>
                      </Stack>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ fontWeight: 700 }}>
          {tab === 'branches' ? (branchForm.id ? 'Edit Branch' : 'New Competitor Branch') : carrierForm.id ? 'Edit Carrier Rate' : 'New Carrier Rate'}
        </DialogTitle>
        <DialogContent>
          {tab === 'branches' ? (
            <Grid container spacing={2} sx={{ mt: 0.5 }}>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel>Branch Name</InputLabel>
                  <TextField value={branchForm.branchname} onChange={(e) => setBranchForm((f) => ({ ...f, branchname: e.target.value }))} />
                </Stack>
              </Grid>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel>Competitor Name</InputLabel>
                  <TextField value={branchForm.competitorname} onChange={(e) => setBranchForm((f) => ({ ...f, competitorname: e.target.value }))} />
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <InputLabel>City</InputLabel>
                  <TextField value={branchForm.city} onChange={(e) => setBranchForm((f) => ({ ...f, city: e.target.value }))} />
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <InputLabel>Address</InputLabel>
                  <TextField value={branchForm.address} onChange={(e) => setBranchForm((f) => ({ ...f, address: e.target.value }))} />
                </Stack>
              </Grid>
            </Grid>
          ) : (
            <Grid container spacing={2} sx={{ mt: 0.5 }}>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel>Carrier Name</InputLabel>
                  <TextField value={carrierForm.carriername} onChange={(e) => setCarrierForm((f) => ({ ...f, carriername: e.target.value }))} />
                </Stack>
              </Grid>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel>Vehicle Type</InputLabel>
                  <TextField value={carrierForm.vehicletype} onChange={(e) => setCarrierForm((f) => ({ ...f, vehicletype: e.target.value }))} />
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <InputLabel>Base Price</InputLabel>
                  <TextField type="number" value={carrierForm.baseprice} onChange={(e) => setCarrierForm((f) => ({ ...f, baseprice: e.target.value }))} />
                </Stack>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Stack spacing={1}>
                  <InputLabel>Price/Km</InputLabel>
                  <TextField type="number" value={carrierForm.priceperkm} onChange={(e) => setCarrierForm((f) => ({ ...f, priceperkm: e.target.value }))} />
                </Stack>
              </Grid>
            </Grid>
          )}
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={() => setDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleSave} sx={{ bgcolor: BRAND }}>
            Save
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default CompetitiveIntel;
