'use client';

import { useEffect, useState, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useAuth } from '@/lib/context/auth-context';
import { getOrganization, updateOrganization } from '@/lib/api/organizations';
import type { OrganizationResponse } from '@/types/api';
import SubscriptionTab from '@/components/organization/SubscriptionTab';
import LicensesTab from '@/components/organization/LicensesTab';

interface OrganizationForm {
  name: string;
  siren: string;
  eori: string;
  contact_phone: string;
  contact_email: string;
  address_street: string;
  address_city: string;
  address_postal_code: string;
  address_country: string;
}

type TabType = 'information' | 'address' | 'subscription' | 'licenses';

export default function OrganizationSettingsPage() {
  const t = useTranslations('dashboard.organizationSettings');
  const { user } = useAuth();
  const searchParams = useSearchParams();
  const [activeTab, setActiveTab] = useState<TabType>('information');

  useEffect(() => {
    const isSuccess = searchParams.get('success') === 'true';
    const isCanceled = searchParams.get('canceled') === 'true';
    const canAccessBilling = user?.role === 'ADMIN' || user?.role === 'MANAGER';
    if ((isSuccess || isCanceled) && canAccessBilling) {
      setActiveTab('subscription');
    }
  }, [searchParams, user?.role]);
  const [organization, setOrganization] = useState<OrganizationResponse | null>(null);
  const [formData, setFormData] = useState<OrganizationForm>({
    name: '',
    siren: '',
    eori: '',
    contact_phone: '',
    contact_email: '',
    address_street: '',
    address_city: '',
    address_postal_code: '',
    address_country: 'FR',
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const canEdit = user?.role === 'ADMIN' || user?.role === 'MANAGER';

  const loadOrganization = useCallback(async () => {
    if (!user?.organizationId) return;

    try {
      setIsLoading(true);
      setError(null);
      const org = await getOrganization(user.organizationId);
      setOrganization(org);
      setFormData({
        name: org.name || '',
        siren: org.siren || '',
        eori: org.eori || '',
        contact_phone: org.contact_phone || '',
        contact_email: org.contact_email || '',
        address_street: org.address?.street || '',
        address_city: org.address?.city || '',
        address_postal_code: org.address?.postalCode || '',
        address_country: org.address?.country || 'FR',
      });
    } catch (err) {
      console.error('Failed to load organization:', err);
      setError(err instanceof Error ? err.message : t('loadFailed'));
    } finally {
      setIsLoading(false);
    }
  }, [user, t]);

  useEffect(() => {
    if (user?.organizationId) {
      loadOrganization();
    }
  }, [user?.organizationId, loadOrganization]);

  const handleChange = (field: keyof OrganizationForm, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    setSuccessMessage(null);
  };

  const handleCancel = () => {
    if (organization) {
      setFormData({
        name: organization.name || '',
        siren: organization.siren || '',
        eori: organization.eori || '',
        contact_phone: organization.contact_phone || '',
        contact_email: organization.contact_email || '',
        address_street: organization.address?.street || '',
        address_city: organization.address?.city || '',
        address_postal_code: organization.address?.postalCode || '',
        address_country: organization.address?.country || 'FR',
      });
      setSuccessMessage(null);
      setError(null);
    }
  };

  const handleSave = async () => {
    if (!user?.organizationId) return;

    try {
      setIsSaving(true);
      setError(null);
      setSuccessMessage(null);

      const updatedOrg = await updateOrganization(user.organizationId, {
        name: formData.name,
        siren: formData.siren,
        eori: formData.eori,
        contact_phone: formData.contact_phone,
        contact_email: formData.contact_email,
        address: {
          street: formData.address_street,
          city: formData.address_city,
          postalCode: formData.address_postal_code,
          country: formData.address_country,
        },
      });

      setOrganization(updatedOrg);
      setSuccessMessage(t('saveSuccess'));
    } catch (err) {
      console.error('Failed to update organization:', err);
      setError(err instanceof Error ? err.message : t('saveFailed'));
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-4 border-blue-600 mb-4"></div>
          <p className="text-gray-600">{t('loading')}</p>
        </div>
      </div>
    );
  }

  if (!organization) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="bg-red-50 border border-red-200 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-red-900 mb-2">{t('errorTitle')}</h3>
          <p className="text-red-700">{error || t('loadError')}</p>
        </div>
      </div>
    );
  }

  const canViewBilling = user?.role === 'ADMIN' || user?.role === 'MANAGER';

  const tabs = [
    {
      id: 'information' as TabType,
      label: t('tabs.information'),
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        </svg>
      ),
    },
    {
      id: 'address' as TabType,
      label: t('tabs.address'),
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
          />
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
          />
        </svg>
      ),
    },
    ...(canViewBilling
      ? [
          {
            id: 'subscription' as TabType,
            label: t('tabs.subscription'),
            icon: (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
                />
              </svg>
            ),
          },
          {
            id: 'licenses' as TabType,
            label: t('tabs.licenses'),
            icon: (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
                />
              </svg>
            ),
          },
        ]
      : []),
  ];

  return (
    <div className="max-w-4xl mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">{t('header.title')}</h1>
        <p className="text-gray-600 mt-2">{t('header.subtitle')}</p>
      </div>

      {successMessage && (activeTab === 'information' || activeTab === 'address') && (
        <div className="mb-6 bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center">
            <svg
              className="w-5 h-5 text-green-600 mr-3"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 13l4 4L19 7"
              />
            </svg>
            <p className="text-green-800 font-medium">{successMessage}</p>
          </div>
        </div>
      )}

      {error && (activeTab === 'information' || activeTab === 'address') && (
        <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-center">
            <svg
              className="w-5 h-5 text-red-600 mr-3"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
            <p className="text-red-800 font-medium">{error}</p>
          </div>
        </div>
      )}

      {!canEdit && (activeTab === 'information' || activeTab === 'address') && (
        <div className="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center">
            <svg
              className="w-5 h-5 text-blue-600 mr-3"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
            <p className="text-blue-800 font-medium">{t('readOnlyWarning')}</p>
          </div>
        </div>
      )}

      <div className="bg-white rounded-lg shadow-md">
        <div className="border-b border-gray-200">
          <nav className="flex -mb-px overflow-x-auto">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex-shrink-0 px-6 py-4 text-sm font-medium border-b-2 transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-600 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <div className="flex items-center space-x-2">
                  {tab.icon}
                  <span>{tab.label}</span>
                </div>
              </button>
            ))}
          </nav>
        </div>

        <div className="p-8">
          {activeTab === 'information' && (
            <div className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('information.name')} <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={e => handleChange('name', e.target.value)}
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  placeholder={t('information.namePlaceholder')}
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('information.siren')}
                  <span className="ml-2 text-xs text-gray-500">({t('information.sirenHint')})</span>
                </label>
                <input
                  type="text"
                  value={formData.siren}
                  onChange={e =>
                    handleChange('siren', e.target.value.replace(/\D/g, '').slice(0, 9))
                  }
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  placeholder={t('information.sirenPlaceholder')}
                  maxLength={9}
                />
                <p className="mt-1 text-xs text-gray-500">{t('information.sirenDigits')}</p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('information.eori')}
                  <span className="ml-2 text-xs text-gray-500">({t('information.eoriHint')})</span>
                </label>
                <input
                  type="text"
                  value={formData.eori}
                  onChange={e => handleChange('eori', e.target.value.toUpperCase())}
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  placeholder={t('information.eoriPlaceholder')}
                  maxLength={17}
                />
                <p className="mt-1 text-xs text-gray-500">{t('information.eoriHelp')}</p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('information.phone')}
                </label>
                <input
                  type="tel"
                  value={formData.contact_phone}
                  onChange={e => handleChange('contact_phone', e.target.value)}
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  placeholder={t('information.phonePlaceholder')}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('information.email')}
                </label>
                <input
                  type="email"
                  value={formData.contact_email}
                  onChange={e => handleChange('contact_email', e.target.value)}
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  placeholder={t('information.emailPlaceholder')}
                />
              </div>
            </div>
          )}

          {activeTab === 'address' && (
            <div className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('address.street')} <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={formData.address_street}
                  onChange={e => handleChange('address_street', e.target.value)}
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  placeholder={t('address.streetPlaceholder')}
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('address.postalCode')} <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.address_postal_code}
                    onChange={e => handleChange('address_postal_code', e.target.value)}
                    disabled={!canEdit}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                    placeholder={t('address.postalCodePlaceholder')}
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('address.city')} <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.address_city}
                    onChange={e => handleChange('address_city', e.target.value)}
                    disabled={!canEdit}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                    placeholder={t('address.cityPlaceholder')}
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('address.country')} <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.address_country}
                  onChange={e => handleChange('address_country', e.target.value)}
                  disabled={!canEdit}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                  required
                >
                  <option value="FR">{t('address.countries.FR')}</option>
                  <option value="BE">{t('address.countries.BE')}</option>
                  <option value="DE">{t('address.countries.DE')}</option>
                  <option value="ES">{t('address.countries.ES')}</option>
                  <option value="IT">{t('address.countries.IT')}</option>
                  <option value="NL">{t('address.countries.NL')}</option>
                  <option value="GB">{t('address.countries.GB')}</option>
                  <option value="US">{t('address.countries.US')}</option>
                  <option value="CN">{t('address.countries.CN')}</option>
                </select>
              </div>
            </div>
          )}

          {activeTab === 'subscription' && canViewBilling && <SubscriptionTab />}

          {activeTab === 'licenses' && canViewBilling && <LicensesTab />}
        </div>

        {canEdit && (activeTab === 'information' || activeTab === 'address') && (
          <div className="bg-gray-50 px-8 py-4 border-t border-gray-200 flex items-center justify-end space-x-4">
            <button
              type="button"
              onClick={handleCancel}
              disabled={isSaving}
              className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {t('actions.cancel')}
            </button>
            <button
              type="button"
              onClick={handleSave}
              disabled={isSaving || !formData.name || !formData.address_street}
              className="px-6 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center"
            >
              {isSaving ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  {t('actions.saving')}
                </>
              ) : (
                t('actions.save')
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
