'use client';

import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { getAllOrganizations, verifySiret, approveSiret, rejectSiret } from '@/lib/api/admin';
import { createOrganization, updateOrganization } from '@/lib/api/organizations';
import { PageHeader } from '@/components/ui/PageHeader';

interface Organization {
  id: string;
  name: string;
  type: string;
  scac?: string;
  siren?: string;
  siret?: string;
  siretVerified?: boolean;
  statusBadge?: string;
  eori?: string;
  contact_phone?: string;
  contact_email?: string;
  address: {
    street: string;
    city: string;
    state?: string;
    postalCode: string;
    country: string;
  };
  logoUrl?: string;
  isActive: boolean;
  createdAt: string;
}

export default function AdminOrganizationsPage() {
  const t = useTranslations('dashboard.admin.organizations');

  const [organizations, setOrganizations] = useState<Organization[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedOrg, setSelectedOrg] = useState<Organization | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [verifyingId, setVerifyingId] = useState<string | null>(null);

  // Form state
  const [formData, setFormData] = useState<{
    name: string;
    type: string;
    scac: string;
    siren: string;
    siret: string;
    eori: string;
    contact_phone: string;
    contact_email: string;
    address: {
      street: string;
      city: string;
      state?: string;
      postalCode: string;
      country: string;
    };
    logoUrl: string;
  }>({
    name: '',
    type: 'FREIGHT_FORWARDER',
    scac: '',
    siren: '',
    siret: '',
    eori: '',
    contact_phone: '',
    contact_email: '',
    address: {
      street: '',
      city: '',
      state: '',
      postalCode: '',
      country: 'FR',
    },
    logoUrl: '',
  });

  useEffect(() => {
    fetchOrganizations();
  }, []);

  const fetchOrganizations = async () => {
    try {
      setLoading(true);
      const response = await getAllOrganizations();
      setOrganizations(response.organizations || []);
      setError(null);
    } catch (err: any) {
      setError(err.message || t('loadError'));
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const apiData = {
        name: formData.name,
        type: formData.type as any,
        address: {
          street: formData.address.street,
          city: formData.address.city,
          postalCode: formData.address.postalCode,
          country: formData.address.country,
          ...(formData.address.state ? { state: formData.address.state } : {}),
        },
        contact_email: formData.contact_email || undefined,
        contact_phone: formData.contact_phone || undefined,
        logo_url: formData.logoUrl || undefined,
        ...(formData.siren ? { siren: formData.siren } : {}),
        ...(formData.siret ? { siret: formData.siret } : {}),
        ...(formData.eori ? { eori: formData.eori } : {}),
        ...(formData.scac ? { scac: formData.scac } : {}),
      };
      await createOrganization(apiData);
      await fetchOrganizations();
      setShowCreateModal(false);
      resetForm();
    } catch (err: any) {
      alert(err.message || t('createError'));
    }
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedOrg) return;

    try {
      await updateOrganization(selectedOrg.id, formData);
      await fetchOrganizations();
      setShowEditModal(false);
      setSelectedOrg(null);
      resetForm();
    } catch (err: any) {
      alert(err.message || t('updateError'));
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      type: 'FREIGHT_FORWARDER',
      scac: '',
      siren: '',
      siret: '',
      eori: '',
      contact_phone: '',
      contact_email: '',
      address: {
        street: '',
        city: '',
        state: '',
        postalCode: '',
        country: 'FR',
      },
      logoUrl: '',
    });
  };

  const handleVerifySiret = async (orgId: string) => {
    try {
      setVerifyingId(orgId);
      const result = await verifySiret(orgId);
      if (result.verified) {
        alert(
          t('siretVerified', {
            companyName: result.companyName || 'N/A',
            address: result.address || 'N/A',
          })
        );
        await fetchOrganizations();
      } else {
        alert(result.message || t('siretInvalid'));
      }
    } catch (err: any) {
      alert(err.message || t('siretError'));
    } finally {
      setVerifyingId(null);
    }
  };

  const handleApproveSiret = async (orgId: string) => {
    if (!confirm(t('confirmApprove'))) return;
    try {
      setVerifyingId(orgId);
      const result = await approveSiret(orgId);
      alert(result.message);
      await fetchOrganizations();
    } catch (err: any) {
      alert(err.message || t('siretApproveError'));
    } finally {
      setVerifyingId(null);
    }
  };

  const handleRejectSiret = async (orgId: string) => {
    if (!confirm(t('confirmReject'))) return;
    try {
      setVerifyingId(orgId);
      const result = await rejectSiret(orgId);
      alert(result.message);
      await fetchOrganizations();
    } catch (err: any) {
      alert(err.message || t('siretRejectError'));
    } finally {
      setVerifyingId(null);
    }
  };

  const openEditModal = (org: Organization) => {
    setSelectedOrg(org);
    setFormData({
      name: org.name,
      type: org.type,
      scac: org.scac || '',
      siren: org.siren || '',
      siret: org.siret || '',
      eori: org.eori || '',
      contact_phone: org.contact_phone || '',
      contact_email: org.contact_email || '',
      address: org.address,
      logoUrl: org.logoUrl || '',
    });
    setShowEditModal(true);
  };

  const getTypeLabel = (type: string) => {
    const allowed = ['FREIGHT_FORWARDER', 'CARRIER', 'SHIPPER'];
    if (allowed.includes(type)) {
      return t(`types.${type}` as any);
    }
    return type.replace('_', ' ');
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">{t('loading')}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={t('title')}
        description={t('subtitle')}
        actions={
          <button
            onClick={() => setShowCreateModal(true)}
            className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
          >
            {t('create')}
          </button>
        }
      />

      {/* Error Message */}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          {error}
        </div>
      )}

      {/* Organizations Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {organizations.map(org => (
          <div key={org.id} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="flex items-start justify-between mb-4">
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-gray-900">{org.name}</h3>
                <span
                  className={`inline-block mt-2 px-2 py-1 text-xs font-semibold rounded-full ${
                    org.type === 'FREIGHT_FORWARDER'
                      ? 'bg-blue-100 text-blue-800'
                      : org.type === 'CARRIER'
                        ? 'bg-green-100 text-green-800'
                        : 'bg-purple-100 text-purple-800'
                  }`}
                >
                  {getTypeLabel(org.type)}
                </span>
              </div>
              <span
                className={`px-2 py-1 text-xs font-semibold rounded-full ${
                  org.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                }`}
              >
                {org.isActive ? t('active') : t('inactive')}
              </span>
            </div>

            <div className="space-y-2 text-sm text-gray-600 mb-4">
              {org.scac && (
                <div>
                  <span className="font-medium">{t('scac')}:</span> {org.scac}
                </div>
              )}
              {org.siren && (
                <div>
                  <span className="font-medium">{t('siren')}:</span> {org.siren}
                </div>
              )}
              <div className="flex items-center gap-2">
                <span className="font-medium">{t('siret')}:</span>
                {org.siret ? (
                  <>
                    <span>{org.siret}</span>
                    {org.siretVerified ? (
                      <span className="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                        {t('verified')}
                      </span>
                    ) : (
                      <span className="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">
                        {t('notVerified')}
                      </span>
                    )}
                  </>
                ) : (
                  <span className="text-gray-400">{t('notProvided')}</span>
                )}
              </div>
              {org.contact_email && (
                <div>
                  <span className="font-medium">{t('email')}:</span> {org.contact_email}
                </div>
              )}
              <div>
                <span className="font-medium">{t('location')}:</span> {org.address.city},{' '}
                {org.address.country}
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex space-x-2">
                <button
                  onClick={() => openEditModal(org)}
                  className="flex-1 px-3 py-2 bg-blue-50 text-blue-700 rounded-md hover:bg-blue-100 transition-colors text-sm font-medium"
                >
                  {t('edit')}
                </button>
                {org.siret && !org.siretVerified && (
                  <button
                    onClick={() => handleVerifySiret(org.id)}
                    disabled={verifyingId === org.id}
                    className="flex-1 px-3 py-2 bg-purple-50 text-purple-700 rounded-md hover:bg-purple-100 transition-colors text-sm font-medium disabled:opacity-50"
                  >
                    {verifyingId === org.id ? t('verifying') : t('verifyApi')}
                  </button>
                )}
              </div>
              {(org.siret || org.siren) && (
                <div className="flex space-x-2">
                  {!org.siretVerified ? (
                    <button
                      onClick={() => handleApproveSiret(org.id)}
                      disabled={verifyingId === org.id}
                      className="flex-1 px-3 py-2 bg-green-50 text-green-700 rounded-md hover:bg-green-100 transition-colors text-sm font-medium disabled:opacity-50"
                    >
                      {t('approveSiret')}
                    </button>
                  ) : (
                    <button
                      onClick={() => handleRejectSiret(org.id)}
                      disabled={verifyingId === org.id}
                      className="flex-1 px-3 py-2 bg-red-50 text-red-700 rounded-md hover:bg-red-100 transition-colors text-sm font-medium disabled:opacity-50"
                    >
                      {t('rejectSiret')}
                    </button>
                  )}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Create/Edit Modal */}
      {(showCreateModal || showEditModal) && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 overflow-y-auto">
          <div className="bg-white rounded-lg p-6 max-w-2xl w-full m-4 max-h-[90vh] overflow-y-auto">
            <h2 className="text-xl font-bold mb-4">
              {showCreateModal ? t('modal.createTitle') : t('modal.editTitle')}
            </h2>
            <form onSubmit={showCreateModal ? handleCreate : handleUpdate} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.name')}
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.name}
                    onChange={e => setFormData({ ...formData, name: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.type')}
                  </label>
                  <select
                    value={formData.type}
                    onChange={e => setFormData({ ...formData, type: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  >
                    <option value="FREIGHT_FORWARDER">{t('types.FREIGHT_FORWARDER')}</option>
                    <option value="CARRIER">{t('types.CARRIER')}</option>
                    <option value="SHIPPER">{t('types.SHIPPER')}</option>
                  </select>
                </div>

                {formData.type === 'CARRIER' && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      {t('modal.scacLabel')}
                    </label>
                    <input
                      type="text"
                      required={formData.type === 'CARRIER'}
                      maxLength={4}
                      value={formData.scac}
                      onChange={e =>
                        setFormData({ ...formData, scac: e.target.value.toUpperCase() })
                      }
                      className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                    />
                  </div>
                )}

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.sirenLabel')}
                  </label>
                  <input
                    type="text"
                    maxLength={9}
                    value={formData.siren}
                    onChange={e => setFormData({ ...formData, siren: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.siretLabel')}
                  </label>
                  <input
                    type="text"
                    maxLength={14}
                    value={formData.siret}
                    onChange={e =>
                      setFormData({ ...formData, siret: e.target.value.replace(/\D/g, '') })
                    }
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                    placeholder={t('modal.siretPlaceholder')}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.eoriLabel')}
                  </label>
                  <input
                    type="text"
                    value={formData.eori}
                    onChange={e => setFormData({ ...formData, eori: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.contactPhone')}
                  </label>
                  <input
                    type="tel"
                    value={formData.contact_phone}
                    onChange={e => setFormData({ ...formData, contact_phone: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.contactEmail')}
                  </label>
                  <input
                    type="email"
                    value={formData.contact_email}
                    onChange={e => setFormData({ ...formData, contact_email: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.street')}
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.address.street}
                    onChange={e =>
                      setFormData({
                        ...formData,
                        address: { ...formData.address, street: e.target.value },
                      })
                    }
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.city')}
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.address.city}
                    onChange={e =>
                      setFormData({
                        ...formData,
                        address: { ...formData.address, city: e.target.value },
                      })
                    }
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.postalCode')}
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.address.postalCode}
                    onChange={e =>
                      setFormData({
                        ...formData,
                        address: { ...formData.address, postalCode: e.target.value },
                      })
                    }
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.state')}
                  </label>
                  <input
                    type="text"
                    value={formData.address.state}
                    onChange={e =>
                      setFormData({
                        ...formData,
                        address: { ...formData.address, state: e.target.value },
                      })
                    }
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.country')}
                  </label>
                  <input
                    type="text"
                    required
                    maxLength={2}
                    value={formData.address.country}
                    onChange={e =>
                      setFormData({
                        ...formData,
                        address: { ...formData.address, country: e.target.value.toUpperCase() },
                      })
                    }
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>

                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-700">
                    {t('modal.logoUrl')}
                  </label>
                  <input
                    type="url"
                    value={formData.logoUrl}
                    onChange={e => setFormData({ ...formData, logoUrl: e.target.value })}
                    className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                  />
                </div>
              </div>

              <div className="flex justify-end space-x-2 pt-4">
                <button
                  type="button"
                  onClick={() => {
                    setShowCreateModal(false);
                    setShowEditModal(false);
                    setSelectedOrg(null);
                    resetForm();
                  }}
                  className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
                >
                  {t('modal.cancel')}
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                >
                  {showCreateModal ? t('modal.create') : t('modal.update')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
