/**
 * PersonalAddressSection
 *
 * Billing address editor rendered inside ProfilePage for PERSONAL accounts.
 * Writes through companiesApi.updateCompany since address lives on the
 * Company entity (same row, companyType=PERSONAL). BUSINESS users never see
 * this; they edit address on /dashboard/company instead.
 *
 * Uses AddressFieldset for the form body so the layout stays in sync with
 * CompanySettingsPage.
 *
 * (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)
 */

import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { MapPin, Loader2, Pencil, X } from 'lucide-react';
import type { Address } from '@archer/domain';
import { AddressFieldset } from '@/components/shared';
import { queryKeys } from '@/lib/query-keys';
import { companiesApi } from '@/infrastructure/http/api/company';
import { authenticatedUserStore } from '@/infrastructure/storage/AuthenticatedUserStore';
import { forceTokenRefresh } from '@/infrastructure/http/auth-refresh';
import { useTranslation } from '@/i18n/TranslationProvider';

export function PersonalAddressSection() {
  const { t } = useTranslation();
  const companyId = authenticatedUserStore.get()?.companyId;
  const queryClient = useQueryClient();

  const { data: company, isLoading } = useQuery({
    queryKey: queryKeys.companies.detail(companyId || ''),
    queryFn: () => companiesApi.getCompany(companyId!),
    enabled: !!companyId,
  });

  const mutation = useMutation({
    mutationFn: (data: Parameters<typeof companiesApi.updateCompany>[1]) =>
      companiesApi.updateCompany(companyId!, data),
    onSuccess: async () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
      queryClient.invalidateQueries({ queryKey: queryKeys.profile.all });
      // Address completion can flip isProfileComplete which gates paid actions —
      // round-trip the JWT so cached identity reflects the new server state.
      try { await forceTokenRefresh(); } catch { /* refresh failure: prior snapshot stays, will heal on next /auth/me */ }
      setEditing(false);
    },
  });

  const [editing, setEditing] = useState(false);
  const [address, setAddress] = useState<Address>({});

  useEffect(() => {
    if (company) setAddress(company.address ?? {});
  }, [company]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    mutation.mutate({
      address: {
        street: address.street || undefined,
        zip: address.zip || undefined,
        city: address.city || undefined,
        country: address.country || undefined,
      },
    });
  };

  const handleCancel = () => {
    if (company) setAddress(company.address ?? {});
    setEditing(false);
  };

  return (
    <div className="bg-card rounded-xl border border-border p-6 shadow-sm">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
          <MapPin className="h-5 w-5 text-muted-foreground" />
          {t('profile.billingAddress')}
        </h2>
        {!editing && !isLoading && (
          <button
            onClick={() => setEditing(true)}
            className="flex items-center gap-1.5 text-sm font-medium text-primary hover:text-primary/80 transition-colors"
          >
            <Pencil className="h-4 w-4" />
            {t('common.edit')}
          </button>
        )}
      </div>

      {isLoading ? (
        <div className="space-y-4">
          {[1, 2, 3, 4].map(i => <div key={i} className="h-6 bg-muted animate-pulse rounded w-48" />)}
        </div>
      ) : editing ? (
        <form onSubmit={handleSubmit} className="space-y-4">
          <AddressFieldset value={address} onChange={setAddress} />
          <div className="flex items-center gap-3 pt-2">
            <button
              type="submit"
              disabled={mutation.isPending}
              className="bg-primary text-primary-foreground px-6 py-2.5 rounded-lg font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center gap-2"
            >
              {mutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
              {t('common.save')}
            </button>
            <button
              type="button"
              onClick={handleCancel}
              className="flex items-center gap-1.5 px-4 py-2.5 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
            >
              <X className="h-4 w-4" />
              {t('common.cancel')}
            </button>
            {mutation.isError && (
              <span className="text-sm text-destructive">{(mutation.error as Error).message || t('profile.updateFailed')}</span>
            )}
          </div>
        </form>
      ) : (
        <div className="space-y-3">
          <div>
            <p className="text-sm text-muted-foreground">{t('address.street')}</p>
            <p className="text-sm font-medium text-foreground mt-0.5">{company?.address?.street || '-'}</p>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <p className="text-sm text-muted-foreground">{t('address.zip')}</p>
              <p className="text-sm font-medium text-foreground mt-0.5">{company?.address?.zip || '-'}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">{t('address.city')}</p>
              <p className="text-sm font-medium text-foreground mt-0.5">{company?.address?.city || '-'}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">{t('address.country')}</p>
              <p className="text-sm font-medium text-foreground mt-0.5">{company?.address?.country || '-'}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
