'use client';
import { FunctionComponent, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import { Box, Divider, MenuItem, Paper, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppIcon, AppLoading, ErrorState, PhoneNumberField } from '@/components';
import LocaleSwitcher from '@/components/common/LocaleSwitcher';
import { isIranianMobile } from '@/components/PhoneNumberField';
import { ROUTES } from '@/constants';
import { digitsOnly } from '@/utils';
import { ActorSwitcher } from '@/layout';
import { useCustomerProfile, useUpsertCustomerProfile } from '@/services/profiles';
import { useMe, useLogout } from '@/services/auth';
import type { CustomerProfile } from '@/services/profiles/types';

/** Customer profile — name, preferred language, and the emergency contact. No national-ID KYC. */
export default function CustomerProfilePage() {
  const t = useTranslations('profile');
  const tc = useTranslations('common');
  const { data: profile, isLoading, isError, refetch } = useCustomerProfile();
  const { data: me } = useMe();
  if (isLoading) return <AppLoading />;
  // The form must never render on a failed fetch — it would otherwise show blank/undefined fields
  // whose save could overwrite server truth.
  if (isError) return <ErrorState message={t('load_error')} retryLabel={tc('retry')} onRetry={() => refetch()} />;
  // The customer name is owned by `/me` (REQ-007), not `CustomerProfileDto` — prefill it from there so
  // editing the emergency contact never blanks (and re-saves as null) the existing name.
  return (
    <CustomerProfileForm initial={profile ?? null} nameFallback={{ firstName: me?.firstName ?? null, lastName: me?.lastName ?? null }} />
  );
}

const CustomerProfileForm: FunctionComponent<{
  initial: CustomerProfile | null;
  nameFallback: { firstName: string | null; lastName: string | null };
}> = ({ initial, nameFallback }) => {
  const t = useTranslations('profile');
  const ta = useTranslations('address');
  const tc = useTranslations('common');
  const locale = useLocale();
  const { enqueueSnackbar } = useSnackbar();
  const upsert = useUpsertCustomerProfile();

  const [firstName, setFirstName] = useState(initial?.firstName ?? nameFallback.firstName ?? '');
  const [lastName, setLastName] = useState(initial?.lastName ?? nameFallback.lastName ?? '');
  const [language, setLanguage] = useState(initial?.preferredLanguage ?? 'fa');
  const [emergencyName, setEmergencyName] = useState(initial?.defaultEmergencyContactName ?? '');
  const [emergencyPhone, setEmergencyPhone] = useState(digitsOnly(initial?.defaultEmergencyContactPhone ?? ''));
  const [nameError, setNameError] = useState(false);
  const [phoneError, setPhoneError] = useState(false);

  const isComplete = Boolean(initial?.defaultEmergencyContactName && initial?.defaultEmergencyContactPhone);

  const handleSave = () => {
    const nameInvalid = emergencyName.trim().length === 0;
    const phoneInvalid = !isIranianMobile(emergencyPhone);
    setNameError(nameInvalid);
    setPhoneError(phoneInvalid);
    if (nameInvalid || phoneInvalid) return;

    upsert.mutate(
      {
        defaultEmergencyContactName: emergencyName.trim(),
        defaultEmergencyContactPhone: emergencyPhone,
        firstName: firstName.trim() || null,
        lastName: lastName.trim() || null,
        preferredLanguage: language,
      },
      { onSuccess: () => enqueueSnackbar(t('saved'), { variant: 'success' }) },
    );
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 520 }}>
      <Box>
        <Typography variant="h5" component="h1">
          {t('title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('subtitle')}
        </Typography>
        <Typography variant="body2" sx={{ mt: 0.5, color: isComplete ? 'var(--bal-success)' : 'text.secondary' }}>
          {isComplete ? t('completion_done') : t('completion_todo')}
        </Typography>
      </Box>

      <Stack direction={{ xs: 'column', sm: 'row' }} sx={{ gap: 2 }}>
        <TextField label={t('first_name')} value={firstName} onChange={(e) => setFirstName(e.target.value)} fullWidth />
        <TextField label={t('last_name')} value={lastName} onChange={(e) => setLastName(e.target.value)} fullWidth />
      </Stack>

      <TextField
        select
        label={t('language')}
        value={language}
        onChange={(e) => setLanguage(e.target.value)}
        sx={{ maxWidth: 220 }}
      >
        <MenuItem value="fa">{t('language_fa')}</MenuItem>
        <MenuItem value="en">{t('language_en')}</MenuItem>
      </TextField>

      <Divider />

      <Box>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('emergency_section')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('emergency_hint')}
        </Typography>
      </Box>

      <TextField
        label={t('emergency_name')}
        value={emergencyName}
        onChange={(e) => {
          setEmergencyName(e.target.value);
          if (nameError) setNameError(false);
        }}
        error={nameError}
        fullWidth
      />
      <PhoneNumberField
        label={t('emergency_phone')}
        value={emergencyPhone}
        onChange={(value) => {
          setEmergencyPhone(value);
          if (phoneError) setPhoneError(false);
        }}
        error={phoneError}
        helperText={phoneError ? t('emergency_phone_invalid') : undefined}
        fullWidth
      />

      <AppButton
        color="primary"
        variant="contained"
        onClick={handleSave}
        disabled={upsert.isPending}
        sx={{ alignSelf: 'flex-start' }}
      >
        {upsert.isPending ? tc('saving') : t('save')}
      </AppButton>

      <Divider />

      {/* Address book lives alongside the profile in the customer area; a booking (f7) needs a
          chosen address, so the entry point is surfaced here on the settings hub. */}
      <Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2, display: 'flex', gap: 2 }}>
        <AppIcon icon="location" size={28} color="var(--bal-primary)" />
        <Stack sx={{ gap: 1, flexGrow: 1 }}>
          <Box>
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {ta('manage_title')}
            </Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {ta('manage_body')}
            </Typography>
          </Box>
          <AppButton
            color="primary"
            variant="outlined"
            startIcon="location"
            to={`/${locale}${ROUTES.ADDRESSES}`}
            sx={{ alignSelf: 'flex-start' }}
          >
            {ta('manage_cta')}
          </AppButton>
        </Stack>
      </Paper>

      <Divider />

      {/* Account affordances: sign-out has no home anywhere in the customer shell yet (a full hub
          redesign is deferred to phase 9) — one labeled row is enough for now. */}
      <Stack sx={{ gap: 1.5 }}>
        <ActorSwitcher target="nurse" />
        <Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'space-between' }}>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('app_language')}
          </Typography>
          <LocaleSwitcher />
        </Stack>
        <SignOutRow />
      </Stack>
    </Box>
  );
};

const SignOutRow: FunctionComponent = () => {
  const t = useTranslations('profile');
  const { mutate: logout, isPending } = useLogout();
  return (
    <AppButton variant="text" color="error" startIcon="logout" onClick={() => logout()} disabled={isPending} sx={{ alignSelf: 'flex-start' }}>
      {t('sign_out')}
    </AppButton>
  );
};
