import { useState, useRef, useCallback, useEffect } from 'react';
import { Box, Button, InputBase, InputAdornment, Stack, Typography } from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import CountrySelect from '../../../components/country-select';
import PhoneField from '../../../components/phone-field';
import { countryCodeToFlag } from '../../utils/format';

interface FieldConfig {
  name: string;
  type: string;
  required: boolean;
}

interface CustomerInfoCardProps {
  form: {
    fields: FieldConfig[];
    values: Record<string, any>;
    onChange: (field: string, value: string | boolean | Record<string, string>) => void;
    errors: Partial<Record<string, string>>;
    checkValid: () => Promise<boolean>;
    validateField: (field: string) => Promise<void>;
    prefetched: boolean;
  };
  isLoggedIn: boolean;
}

const fieldLabelMap = (t: (key: string) => string) =>
  ({
    customer_name: t('payment.checkout.customer.name'),
    customer_email: t('payment.checkout.customer.email'),
    customer_phone: t('payment.checkout.customer.phone'),
    'billing_address.country': t('payment.checkout.billing.country'),
    'billing_address.state': t('payment.checkout.billing.state'),
    'billing_address.city': t('payment.checkout.billing.city'),
    'billing_address.line1': t('payment.checkout.billing.line1'),
    'billing_address.line2': t('payment.checkout.billing.line2'),
    'billing_address.postal_code': t('payment.checkout.billing.postal_code'),
  }) as Record<string, string>;

export default function CustomerInfoCard({ form, isLoggedIn }: CustomerInfoCardProps) {
  const { t } = useLocaleContext();
  const labels = fieldLabelMap(t);

  // Don't render until first validation completes — avoids flash.
  // Valid → show collapsed summary; invalid → show expanded form.
  // After first check, only manual "Edit"/"Confirm" toggles.
  const [showEditForm, setShowEditForm] = useState(false);
  const [ready, setReady] = useState(false);
  const checkedRef = useRef(false);

  useEffect(() => {
    if (checkedRef.current) return;
    // Wait for data to arrive before making a decision
    if (!form.prefetched && !form.values.customer_name && !form.values.customer_email) return;
    checkedRef.current = true;
    form.checkValid().then((valid) => {
      setShowEditForm(!valid);
      setReady(true);
    });
  }, [form.prefetched]); // eslint-disable-line react-hooks/exhaustive-deps

  // Wrap onChange to delegate to parent form
  const handleChange: typeof form.onChange = useCallback(
    (field, value) => form.onChange(field, value),
    [form.onChange] // eslint-disable-line react-hooks/exhaustive-deps
  );

  // Auto-expand to edit mode when validation errors appear (e.g. after submit click)
  useEffect(() => {
    if (ready && !showEditForm && Object.keys(form.errors).length > 0) {
      setShowEditForm(true);
    }
  }, [form.errors]); // eslint-disable-line react-hooks/exhaustive-deps

  if (!isLoggedIn || !ready) return null;

  // Summary view
  if (!showEditForm) {
    return (
      <Box sx={{ mt: 2 }}>
        {/* Header — outside the card */}
        <Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 1 }}>
          <Typography sx={{ fontSize: 13, fontWeight: 600, color: 'text.secondary' }}>
            {t('payment.checkout.customerInfo')}
          </Typography>
          <Button
            size="small"
            variant="text"
            onClick={() => setShowEditForm(true)}
            sx={{ minWidth: 0, fontSize: 13, fontWeight: 600, p: 0 }}>
            {t('common.edit')}
          </Button>
        </Stack>
        {/* Card body */}
        <Stack
          spacing={0.5}
          sx={{
            p: 2,
            backgroundColor: 'background.paper',
            borderRadius: 1,
            border: '1px solid',
            borderColor: 'divider',
          }}>
          {form.values.customer_name && (
            <Typography variant="body2" sx={{ color: 'text.primary', fontWeight: 600, fontSize: '0.9375rem' }}>
              {form.values.customer_name}
            </Typography>
          )}
          {form.values.customer_email && (
            <Typography variant="body2" sx={{ color: 'text.secondary', fontSize: '0.8125rem' }}>
              {form.values.customer_email}
            </Typography>
          )}
          {form.fields.some((f) => f.name === 'customer_phone') && form.values.customer_phone && (
            <Typography variant="body2" sx={{ color: 'text.secondary', fontSize: '0.8125rem' }}>
              {form.values.customer_phone}
            </Typography>
          )}
          {(form.values.billing_address?.country ||
            form.values.billing_address?.state ||
            form.values.billing_address?.postal_code) && (
            <Stack direction="row" alignItems="center" spacing={0.75}>
              {form.values.billing_address?.country && (
                <Box component="span" sx={{ fontSize: 14, lineHeight: 1 }}>
                  {countryCodeToFlag(form.values.billing_address.country)}
                </Box>
              )}
              <Typography variant="body2" sx={{ color: 'text.secondary', fontSize: '0.8125rem' }}>
                {form.values.billing_address?.state || ''}
                {form.values.billing_address?.postal_code
                  ? ` [ ${t('payment.checkout.billing.postal_code')}: ${form.values.billing_address.postal_code} ]`
                  : ''}
              </Typography>
            </Stack>
          )}
        </Stack>
      </Box>
    );
  }

  // Edit form — v1 style: bold label above, grey background input
  return (
    <Box sx={{ mt: 2 }}>
      {/* Header — outside the card */}
      <Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 1 }}>
        <Typography sx={{ fontSize: 13, fontWeight: 600, color: 'text.secondary' }}>
          {t('payment.checkout.customerInfo')}
        </Typography>
        <Button
          size="small"
          variant="text"
          onClick={() => setShowEditForm(false)}
          sx={{ minWidth: 0, fontSize: 13, fontWeight: 600, p: 0 }}>
          {t('common.confirm')}
        </Button>
      </Stack>
      {/* Card body */}
      <Stack
        spacing={0}
        sx={{
          p: 2,
          backgroundColor: 'background.paper',
          borderRadius: 1,
          border: '1px solid',
          borderColor: 'divider',
        }}>
        {form.fields
          .filter((f) => f.name !== 'billing_address.country')
          .map((field) => {
            const { name } = field;
            const label = labels[name] || name;
            const value = name.includes('.')
              ? name.split('.').reduce((o: any, k) => o?.[k], form.values)
              : form.values[name];
            const isPostalCode = name === 'billing_address.postal_code';
            const isPhone = name === 'customer_phone';

            // Phone field — with country flag + dial code selector
            if (isPhone) {
              return (
                <PhoneField
                  key={name}
                  value={value || ''}
                  country={form.values.billing_address?.country || ''}
                  onChange={(phone) => handleChange('customer_phone', phone)}
                  onCountryChange={(c) => handleChange('billing_address.country', c)}
                  onBlur={() => form.validateField(name)}
                  label={label}
                  error={form.errors[name]}
                />
              );
            }

            return (
              <Box key={name} sx={{ mb: 1.5 }}>
                <Typography sx={{ fontSize: 13, fontWeight: 600, color: 'text.primary', mb: 0.5 }}>{label}</Typography>
                <InputBase
                  fullWidth
                  value={value || ''}
                  onChange={(e) => handleChange(name, e.target.value)}
                  onBlur={() => form.validateField(name)}
                  startAdornment={
                    isPostalCode ? (
                      <InputAdornment position="start" sx={{ mr: 0.5, ml: -0.5 }}>
                        <CountrySelect
                          value={form.values.billing_address?.country || ''}
                          onChange={(v) => handleChange('billing_address.country', v)}
                          sx={{
                            '.MuiOutlinedInput-notchedOutline': { borderColor: 'transparent !important' },
                            '& .MuiSelect-select': { py: 0, pr: '20px !important' },
                          }}
                        />
                      </InputAdornment>
                    ) : undefined
                  }
                  sx={{
                    bgcolor: (theme) => (theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.06)' : 'grey.50'),
                    borderRadius: '8px',
                    px: 1.5,
                    py: 0.75,
                    fontSize: 14,
                    '& .MuiInputBase-input': { p: 0 },
                  }}
                />
                {form.errors[name] && (
                  <Typography sx={{ fontSize: 12, color: 'error.main', mt: 0.25 }}>{form.errors[name]}</Typography>
                )}
              </Box>
            );
          })}
      </Stack>
    </Box>
  );
}
