import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus, Store, MapPin, Trash2, Edit2, Building2, X, Phone, Mail, Clock, Tag, Globe } from 'lucide-react';
import Button from '../../../ui/Button/Button';
import Card from '../../../ui/Card/Card';
import { Modal, ModalHeader, ModalBody, ModalFooter } from '../../../ui/Modal';
import { Input } from '../../../ui/Input';
import { Select } from '../../../ui/Select';
import { AddressAutocomplete } from '../../../ui/AddressAutocomplete';

export interface ChildTenantSetupStepProps {
  onUpdate?: (data: { childTenants: ChildTenant[]; canContinue: boolean }) => void;
  onComplete?: (data: { childTenants: ChildTenant[] }) => void;
  initialData?: {
    childTenants?: ChildTenant[];
  };
}

export interface ChildTenant {
  id: string;
  name: string;
  city: string;
  zone?: string;
  address: string;
  postal_code: string;
  location_code: string;
  latitude?: number;
  longitude?: number;
  phone?: string;
  email?: string;
  business_type?: string;
  business_model?: string;
  timezone?: string;
  metadata?: Record<string, any>;
}

export const ChildTenantsSetupStep: React.FC<ChildTenantSetupStepProps> = ({
  onUpdate,
  onComplete,
  initialData,
}) => {
  const { t } = useTranslation();
  const [childTenants, setChildTenants] = useState<ChildTenant[]>(
    initialData?.childTenants || []
  );
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingTenant, setEditingTenant] = useState<ChildTenant | null>(null);
  const [formData, setFormData] = useState<Partial<ChildTenant>>({
    name: '',
    city: '',
    zone: '',
    address: '',
    postal_code: '',
    location_code: '',
    latitude: undefined,
    longitude: undefined,
    phone: '',
    email: '',
    business_type: 'bakery',
    business_model: 'retail_bakery',
    timezone: 'Europe/Madrid',
    metadata: {},
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // Notify parent when child tenants change
  React.useEffect(() => {
    onUpdate?.({
      childTenants,
      canContinue: childTenants.length > 0 // Require at least one child tenant
    });
  }, [childTenants, onUpdate]);

  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!formData.name?.trim()) {
      errors.name = t('onboarding:child_tenants.validation.name_required');
    }
    if (!formData.city?.trim()) {
      errors.city = t('onboarding:child_tenants.validation.city_required');
    }
    if (!formData.address?.trim()) {
      errors.address = t('onboarding:child_tenants.validation.address_required');
    }
    if (!formData.postal_code?.trim()) {
      errors.postal_code = t('onboarding:child_tenants.validation.postal_code_required');
    } else if (!/^\d{5}$/.test(formData.postal_code)) {
      errors.postal_code = t('onboarding:child_tenants.validation.postal_code_format');
    }
    if (!formData.location_code?.trim()) {
      errors.location_code = t('onboarding:child_tenants.validation.location_code_required');
    } else if (formData.location_code.length > 10) {
      errors.location_code = t('onboarding:child_tenants.validation.location_code_max');
    } else if (!/^[A-Z0-9\-_.]+$/.test(formData.location_code)) {
      errors.location_code = t('onboarding:child_tenants.validation.location_code_format');
    }

    // Phone validation
    if (formData.phone && formData.phone.trim()) {
      const phone = formData.phone.replace(/[\s\-\(\)]/g, '');
      const patterns = [
        /^(\+34|0034|34)?[6789]\d{8}$/, // Mobile
        /^(\+34|0034|34)?9\d{8}$/       // Landline
      ];
      if (!patterns.some(pattern => pattern.test(phone))) {
        errors.phone = t('onboarding:child_tenants.validation.phone_format');
      }
    }

    // Email validation
    if (formData.email && formData.email.trim()) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        errors.email = t('onboarding:child_tenants.validation.email_format');
      }
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleOpenModal = (tenant?: ChildTenant) => {
    if (tenant) {
      setEditingTenant(tenant);
      setFormData({ ...tenant });
    } else {
      setEditingTenant(null);
      setFormData({
        name: '',
        city: '',
        zone: '',
        address: '',
        postal_code: '',
        location_code: '',
      });
    }
    setFormErrors({});
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setEditingTenant(null);
    setFormData({
      name: '',
      city: '',
      zone: '',
      address: '',
      postal_code: '',
      location_code: '',
    });
    setFormErrors({});
  };

  const handleSaveTenant = () => {
    if (!validateForm()) return;

    const tenant: ChildTenant = {
      id: editingTenant?.id || `child-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      name: formData.name!,
      city: formData.city!,
      zone: formData.zone,
      address: formData.address!,
      postal_code: formData.postal_code!,
      location_code: formData.location_code!.toUpperCase(),
      latitude: formData.latitude,
      longitude: formData.longitude,
      phone: formData.phone || undefined,
      email: formData.email || undefined,
      business_type: formData.business_type || 'bakery',
      business_model: formData.business_model || 'retail_bakery',
      timezone: formData.timezone || 'Europe/Madrid',
      metadata: formData.metadata || {},
    };

    if (editingTenant) {
      // Update existing
      setChildTenants(prev => prev.map(t => t.id === editingTenant.id ? tenant : t));
    } else {
      // Add new
      setChildTenants(prev => [...prev, tenant]);
    }

    handleCloseModal();
  };

  const handleDeleteTenant = (id: string) => {
    setChildTenants(prev => prev.filter(t => t.id !== id));
  };

  const handleContinue = () => {
    if (childTenants.length === 0) {
      alert(t('onboarding:child_tenants.alerts.require_one'));
      return;
    }
    onComplete?.({ childTenants });
  };

  return (
    <div className="max-w-4xl mx-auto p-4 md:p-6 space-y-6">
      {/* Header */}
      <div className="text-center space-y-3">
        <div className="flex items-center justify-center gap-3">
          <Building2 className="w-10 h-10 text-[var(--color-primary)]" />
          <h1 className="text-2xl md:text-3xl font-bold text-[var(--text-primary)]">
            {t('onboarding:child_tenants.title')}
          </h1>
        </div>
        <p className="text-base md:text-lg text-[var(--text-secondary)] max-w-2xl mx-auto">
          {t('onboarding:child_tenants.subtitle')}
        </p>
      </div>

      {/* Info Box */}
      <div className="bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <div className="text-[var(--color-info)] mt-0.5">
            <Store className="w-5 h-5" />
          </div>
          <div className="space-y-1">
            <h4 className="font-semibold text-[var(--text-primary)]">
              {t('onboarding:child_tenants.info_box.title')}
            </h4>
            <p className="text-sm text-[var(--text-secondary)]">
              {t('onboarding:child_tenants.info_box.description')}
            </p>
          </div>
        </div>
      </div>

      {/* Child Tenants List */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold text-[var(--text-primary)]">
            {t('onboarding:child_tenants.list.title')} ({childTenants.length})
          </h2>
          <Button
            onClick={() => handleOpenModal()}
            variant="primary"
            size="md"
            leftIcon={<Plus className="w-4 h-4" />}
          >
            {t('onboarding:child_tenants.list.add_button')}
          </Button>
        </div>

        {childTenants.length === 0 ? (
          <Card className="p-8 text-center">
            <div className="space-y-4">
              <div className="w-16 h-16 mx-auto bg-[var(--bg-tertiary)] rounded-full flex items-center justify-center">
                <Store className="w-8 h-8 text-[var(--text-tertiary)]" />
              </div>
              <div>
                <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
                  {t('onboarding:child_tenants.list.empty_state.title')}
                </h3>
                <p className="text-sm text-[var(--text-secondary)] mb-4">
                  {t('onboarding:child_tenants.list.empty_state.description')}
                </p>
                <Button
                  onClick={() => handleOpenModal()}
                  variant="primary"
                  size="lg"
                  leftIcon={<Plus className="w-5 h-5" />}
                >
                  {t('onboarding:child_tenants.list.empty_state.button')}
                </Button>
              </div>
            </div>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {childTenants.map((tenant) => (
              <Card key={tenant.id} className="p-4 hover:shadow-md transition-shadow">
                <div className="space-y-3">
                  {/* Header */}
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-2">
                      <div className="w-10 h-10 bg-[var(--color-primary)]/10 rounded-lg flex items-center justify-center">
                        <Store className="w-5 h-5 text-[var(--color-primary)]" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-[var(--text-primary)]">
                          {tenant.name}
                        </h3>
                        <div className="flex gap-2">
                          <span className="text-xs text-[var(--text-tertiary)] font-mono">
                            {tenant.location_code}
                          </span>
                          {tenant.zone && (
                            <span className="text-xs text-[var(--text-tertiary)]">
                              • {tenant.zone}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="flex gap-1">
                      <button
                        onClick={() => handleOpenModal(tenant)}
                        className="p-2 hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors"
                        title={t('onboarding:child_tenants.card.edit')}
                      >
                        <Edit2 className="w-4 h-4 text-[var(--text-secondary)]" />
                      </button>
                      <button
                        onClick={() => handleDeleteTenant(tenant.id)}
                        className="p-2 hover:bg-[var(--color-error)]/10 rounded-lg transition-colors"
                        title={t('onboarding:child_tenants.card.delete')}
                      >
                        <Trash2 className="w-4 h-4 text-[var(--color-error)]" />
                      </button>
                    </div>
                  </div>

                  {/* Location Details */}
                  <div className="space-y-1 text-sm">
                    <div className="flex items-start gap-2 text-[var(--text-secondary)]">
                      <MapPin className="w-4 h-4 mt-0.5 flex-shrink-0" />
                      <div>
                        <div>{tenant.address}</div>
                        <div>
                          {tenant.postal_code} - {tenant.city}
                          {tenant.zone && <>, {tenant.zone}</>}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Continue Button */}
      {childTenants.length > 0 && (
        <div className="flex justify-center pt-4">
          <Button
            onClick={handleContinue}
            variant="primary"
            size="lg"
            className="w-full sm:w-auto sm:min-w-[200px]"
          >
            {t('onboarding:child_tenants.continue_button', { count: childTenants.length })}
          </Button>
        </div>
      )}

      {/* Add/Edit Modal */}
      <Modal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        size="lg"
      >
        <ModalHeader
          title={t(editingTenant ? 'onboarding:child_tenants.modal.title_edit' : 'onboarding:child_tenants.modal.title_add')}
          showCloseButton
          onClose={handleCloseModal}
        />
        <ModalBody padding="lg">
          <div className="space-y-4">
            {/* Name */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.name')} *
              </label>
              <Input
                value={formData.name || ''}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder={t('onboarding:child_tenants.modal.placeholders.name')}
                error={formErrors.name}
              />
            </div>

            {/* Location Code */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.location_code')} * {t('onboarding:child_tenants.modal.fields.location_code_max')}
              </label>
              <Input
                value={formData.location_code || ''}
                onChange={(e) => setFormData({ ...formData, location_code: e.target.value.toUpperCase() })}
                placeholder={t('onboarding:child_tenants.modal.placeholders.location_code')}
                maxLength={10}
                error={formErrors.location_code}
              />
              <p className="text-xs text-[var(--text-tertiary)] mt-1">
                {t('onboarding:child_tenants.modal.fields.location_code_help')}
              </p>
            </div>

            {/* Business Type */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.business_type')}
              </label>
              <Select
                value={formData.business_type || 'bakery'}
                onChange={(e) => setFormData({ ...formData, business_type: e.target.value })}
              >
                <option value="bakery">{t('onboarding:child_tenants.modal.business_types.bakery')}</option>
                <option value="coffee_shop">{t('onboarding:child_tenants.modal.business_types.coffee_shop')}</option>
                <option value="pastry_shop">{t('onboarding:child_tenants.modal.business_types.pastry_shop')}</option>
                <option value="restaurant">{t('onboarding:child_tenants.modal.business_types.restaurant')}</option>
              </Select>
            </div>

            {/* Business Model */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.business_model')}
              </label>
              <Select
                value={formData.business_model || 'retail_bakery'}
                onChange={(e) => setFormData({ ...formData, business_model: e.target.value })}
              >
                <option value="retail_bakery">{t('onboarding:child_tenants.modal.business_models.retail_bakery')}</option>
                <option value="central_baker_satellite">{t('onboarding:child_tenants.modal.business_models.central_baker_satellite')}</option>
                <option value="hybrid_bakery">{t('onboarding:child_tenants.modal.business_models.hybrid_bakery')}</option>
              </Select>
            </div>

            {/* Contact Info */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                  {t('onboarding:child_tenants.modal.fields.phone')}
                </label>
                <div className="relative">
                  <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-[var(--text-secondary)]" />
                  <Input
                    value={formData.phone || ''}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    placeholder={t('onboarding:child_tenants.modal.placeholders.phone')}
                    error={formErrors.phone}
                    className="pl-10"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                  {t('onboarding:child_tenants.modal.fields.email')}
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-[var(--text-secondary)]" />
                  <Input
                    value={formData.email || ''}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    placeholder={t('onboarding:child_tenants.modal.placeholders.email')}
                    error={formErrors.email}
                    className="pl-10"
                  />
                </div>
              </div>
            </div>

            {/* Timezone */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.timezone')}
              </label>
              <div className="relative">
                <Clock className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-[var(--text-secondary)]" />
                <Select
                  value={formData.timezone || 'Europe/Madrid'}
                  onChange={(e) => setFormData({ ...formData, timezone: e.target.value })}
                  className="pl-10"
                >
                  <option value="Europe/Madrid">{t('onboarding:child_tenants.modal.timezones.europe_madrid')}</option>
                  <option value="Europe/Paris">{t('onboarding:child_tenants.modal.timezones.europe_paris')}</option>
                  <option value="Europe/London">{t('onboarding:child_tenants.modal.timezones.europe_london')}</option>
                  <option value="America/New_York">{t('onboarding:child_tenants.modal.timezones.america_new_york')}</option>
                </Select>
              </div>
            </div>

            {/* Zone */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.zone')}
              </label>
              <Input
                value={formData.zone || ''}
                onChange={(e) => setFormData({ ...formData, zone: e.target.value })}
                placeholder={t('onboarding:child_tenants.modal.placeholders.zone')}
              />
              <p className="text-xs text-[var(--text-tertiary)] mt-1">
                {t('onboarding:child_tenants.modal.fields.zone_help')}
              </p>
            </div>

            {/* Address with Autocomplete */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('onboarding:child_tenants.modal.fields.address')} *
              </label>
              <AddressAutocomplete
                value={formData.address || ''}
                placeholder={t('onboarding:child_tenants.modal.placeholders.address')}
                onAddressSelect={(address) => {
                  setFormData(prev => ({
                    ...prev,
                    address: address.display_name,
                    city: address.address.city || address.address.municipality || address.address.suburb || prev.city,
                    postal_code: address.address.postcode || prev.postal_code,
                    latitude: address.lat,
                    longitude: address.lon,
                  }));
                }}
                onCoordinatesChange={(lat, lon) => {
                  setFormData(prev => ({
                    ...prev,
                    latitude: lat,
                    longitude: lon,
                  }));
                }}
                countryCode="es"
                required
              />
              {formErrors.address && (
                <div className="mt-1 text-sm text-[var(--color-error)]">
                  {formErrors.address}
                </div>
              )}
            </div>

            {/* City and Postal Code */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                  {t('onboarding:child_tenants.modal.fields.city')} *
                </label>
                <Input
                  value={formData.city || ''}
                  onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                  placeholder={t('onboarding:child_tenants.modal.placeholders.city')}
                  error={formErrors.city}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                  {t('onboarding:child_tenants.modal.fields.postal_code')} *
                </label>
                <Input
                  value={formData.postal_code || ''}
                  onChange={(e) => setFormData({ ...formData, postal_code: e.target.value })}
                  placeholder={t('onboarding:child_tenants.modal.placeholders.postal_code')}
                  error={formErrors.postal_code}
                  maxLength={5}
                />
              </div>
            </div>
          </div>
        </ModalBody>
        <ModalFooter justify="end">
          <div className="flex gap-3">
            <Button variant="outline" onClick={handleCloseModal}>
              {t('onboarding:child_tenants.modal.buttons.cancel')}
            </Button>
            <Button variant="primary" onClick={handleSaveTenant}>
              {t(editingTenant ? 'onboarding:child_tenants.modal.buttons.save' : 'onboarding:child_tenants.modal.buttons.add')}
            </Button>
          </div>
        </ModalFooter>
      </Modal>
    </div>
  );
};

export default ChildTenantsSetupStep;
