import { useState } from 'react';
import { Avatar, Box, Button, Chip, Grid, InputLabel, Paper, Stack, TextField, Typography } from '@mui/material';
import { useMutation, useQuery } from '@tanstack/react-query';
import { MdBadge, MdPerson, MdLocationOn, MdMail, MdShield, MdVerifiedUser, MdLock } from 'react-icons/md';
import CircularLoader from 'components/CircularLoader';
import Loader from 'components/Loader';
import { getusers } from 'pages/api/api';
import { updateProfilePassword } from 'pages/api/doormileApi';
import { enqueueSnackbar } from 'notistack';

const ROLE_LABELS = { 1: 'Admin', 3: 'Manager', 4: 'Executive' };

// ---- shared design tokens (mirrors the DT block used across the console) ----
const DT = {
  radiusCard: 16,
  radiusInner: 12,
  shadowSoft: '0 14px 40px rgba(15, 23, 42, 0.10)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};
const BRAND = '#C01227';
const BRAND_LIGHT = '#D25463';
const tint = (c) => `${c}08`;
const soft = (c) => `${c}18`;

const initialsOf = (name) =>
  (name || '')
    .trim()
    .split(/\s+/)
    .slice(0, 2)
    .map((w) => w[0])
    .join('')
    .toUpperCase() || '–';

// A single read-only field rendered as an icon + uppercase label + value.
const InfoField = ({ icon: Icon, label, value, accent = BRAND }) => (
  <Stack direction="row" spacing={1.5} alignItems="flex-start" sx={{ minWidth: 0 }}>
    <Avatar sx={{ width: 36, height: 36, bgcolor: soft(accent), color: accent, flexShrink: 0 }}>
      <Icon size={18} />
    </Avatar>
    <Box sx={{ minWidth: 0 }}>
      <Typography
        variant="overline"
        sx={{ display: 'block', color: DT.textMuted, lineHeight: 1.6, letterSpacing: '0.06em' }}
      >
        {label}
      </Typography>
      <Typography
        variant="body1"
        sx={{ fontWeight: 600, color: DT.textPrimary, wordBreak: 'break-word' }}
        title={value || ''}
      >
        {value || '—'}
      </Typography>
    </Box>
  </Stack>
);

// A titled grouping card.
const SectionCard = ({ title, icon: Icon, children }) => (
  <Paper
    elevation={0}
    sx={{
      borderRadius: DT.radiusCard + 'px',
      border: `1px solid ${DT.borderSubtle}`,
      boxShadow: DT.shadowSoft,
      overflow: 'hidden',
      height: '100%'
    }}
  >
    <Stack
      direction="row"
      alignItems="center"
      spacing={1.25}
      sx={{ px: 2.5, py: 1.75, borderBottom: `1px solid ${DT.divider}`, bgcolor: DT.surfaceAlt }}
    >
      <Avatar sx={{ width: 28, height: 28, bgcolor: soft(BRAND), color: BRAND }}>
        <Icon size={16} />
      </Avatar>
      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
        {title}
      </Typography>
    </Stack>
    <Box sx={{ p: 2.5 }}>{children}</Box>
  </Paper>
);

const ViewProfile = () => {
  const { data: userData, isLoading } = useQuery({
    queryKey: ['getuser'],
    queryFn: getusers
  });

  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const changePasswordMutation = useMutation({
    mutationFn: () => updateProfilePassword(currentPassword, newPassword),
    onSuccess: (res) => {
      if (res.success) {
        enqueueSnackbar('Password updated successfully', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
      } else {
        enqueueSnackbar(res.message || 'Failed to update password', {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
      }
    },
    onError: (err) => {
      enqueueSnackbar(err.response?.data?.message || err.message || 'Failed to update password', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
    }
  });

  const handleChangePassword = () => {
    if (!currentPassword || !newPassword) {
      enqueueSnackbar('Fill current and new password', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
      return;
    }
    if (newPassword !== confirmPassword) {
      enqueueSnackbar('New password and confirmation do not match', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
      return;
    }
    changePasswordMutation.mutate();
  };

  // GET /admin/profile has no documented schema, but the console's own login
  // response ({ success, token, user: { id, name, email, role, tenantid } })
  // is confirmed — /admin/profile almost certainly returns the same "user"
  // shape. Fields like address/suburb/city/postcode were jupiter-era guesses
  // with no basis in the new API and have been dropped rather than shown blank.
  const fullname = userData?.name || userData?.fullname || 'User Profile';
  const roleLabel = ROLE_LABELS[userData?.role] || ROLE_LABELS[userData?.roleid] || userData?.role || '—';
  const tenantLabel = userData?.tenantid ? `Tenant #${userData.tenantid}` : 'Doormile staff (all tenants)';

  return (
    <>
      {isLoading && (
        <>
          <Loader />
          <CircularLoader />
        </>
      )}

      <Box sx={{ p: { xs: 1.5, md: 0 } }}>
        {/* ---- Gradient brand header ---- */}
        <Paper
          elevation={0}
          sx={{
            borderRadius: DT.radiusCard + 'px',
            border: `1px solid ${DT.borderSubtle}`,
            background: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)`,
            boxShadow: DT.shadowSoft,
            p: { xs: 2.5, md: 3.5 },
            mb: { xs: 2.5, md: 3 }
          }}
        >
          <Stack
            direction={{ xs: 'column', sm: 'row' }}
            spacing={{ xs: 2, sm: 3 }}
            alignItems={{ xs: 'flex-start', sm: 'center' }}
          >
            <Avatar
              sx={{
                width: { xs: 64, md: 76 },
                height: { xs: 64, md: 76 },
                bgcolor: BRAND,
                color: '#fff',
                fontSize: { xs: 24, md: 28 },
                fontWeight: 700,
                boxShadow: '0 10px 24px rgba(192, 18, 39, 0.35)'
              }}
            >
              {initialsOf(fullname)}
            </Avatar>
            <Box sx={{ minWidth: 0 }}>
              <Typography variant="h3" sx={{ color: DT.textPrimary, fontWeight: 700, mb: 0.5 }}>
                {fullname}
              </Typography>
              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap alignItems="center">
                {roleLabel && (
                  <Chip
                    size="small"
                    icon={<MdVerifiedUser size={14} style={{ color: BRAND }} />}
                    label={roleLabel}
                    sx={{
                      bgcolor: soft(BRAND),
                      color: BRAND,
                      fontWeight: 700,
                      border: `1px solid ${BRAND}40`,
                      '& .MuiChip-icon': { ml: '6px' }
                    }}
                  />
                )}
                {(userData?.id != null || userData?.userid != null) && (
                  <Typography variant="body2" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                    ID&nbsp;#{userData.id ?? userData.userid}
                  </Typography>
                )}
                <Stack direction="row" spacing={0.5} alignItems="center" sx={{ color: DT.textSecondary }}>
                  <MdLocationOn size={15} />
                  <Typography variant="body2" sx={{ fontWeight: 600 }}>
                    {tenantLabel}
                  </Typography>
                </Stack>
              </Stack>
            </Box>
          </Stack>
        </Paper>

        {/* ---- Grouped detail cards ---- */}
        <Grid container spacing={{ xs: 2.5, md: 3 }}>
          <Grid item xs={12} md={6}>
            <SectionCard title="Account" icon={MdBadge}>
              <Stack spacing={2.5}>
                <InfoField icon={MdPerson} label="User Name" value={userData?.name || userData?.fullname} />
                <InfoField icon={MdBadge} label="User ID" value={userData?.id ?? userData?.userid} />
                <InfoField icon={MdMail} label="E-Mail" value={userData?.email} accent="#0ea5e9" />
                <InfoField icon={MdVerifiedUser} label="Role" value={roleLabel} />
                <InfoField icon={MdLocationOn} label="Tenant" value={tenantLabel} accent="#14b8a6" />
              </Stack>
            </SectionCard>
          </Grid>

          <Grid item xs={12} md={6}>
            <SectionCard title="Security" icon={MdShield}>
              <Stack spacing={2}>
                <Stack spacing={1}>
                  <InputLabel htmlFor="current-password">Current Password</InputLabel>
                  <TextField
                    id="current-password"
                    type="password"
                    fullWidth
                    placeholder="Current password"
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    autoComplete="off"
                  />
                </Stack>
                <Stack spacing={1}>
                  <InputLabel htmlFor="new-password">New Password</InputLabel>
                  <TextField
                    id="new-password"
                    type="password"
                    fullWidth
                    placeholder="New password"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    autoComplete="off"
                  />
                </Stack>
                <Stack spacing={1}>
                  <InputLabel htmlFor="confirm-password">Confirm New Password</InputLabel>
                  <TextField
                    id="confirm-password"
                    type="password"
                    fullWidth
                    placeholder="Confirm new password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    autoComplete="off"
                  />
                </Stack>
                <Button
                  variant="contained"
                  startIcon={<MdLock size={16} />}
                  onClick={handleChangePassword}
                  disabled={changePasswordMutation.isPending}
                  sx={{ alignSelf: 'flex-start' }}
                >
                  Update Password
                </Button>
              </Stack>
            </SectionCard>
          </Grid>
        </Grid>
      </Box>
    </>
  );
};

export default ViewProfile;
