import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import apiClient from '../api/client';
import { useBusiness } from '../context/BusinessContext';

function getMissingProviderFields(profile) {
  const provider = profile?.provider || {};
  const missing = [];

  if (!provider.providerName) missing.push('Provider Name');
  if (!provider.senderId) missing.push('Sender ID');
  if (!provider.dltEntityId) missing.push('DLT Entity ID');

  return missing;
}

function isProviderSetupComplete(profile) {
  return getMissingProviderFields(profile).length === 0;
}

function formatUpdatedAt(value) {
  if (!value) return 'Not updated yet';

  try {
    return new Date(value).toLocaleString();
  } catch {
    return 'Not updated yet';
  }
}

function buildProviderSummary(profile) {
  const provider = profile?.provider || {};
  const parts = [];

  if (provider.providerName) parts.push(provider.providerName);
  if (provider.senderId) parts.push(`Sender ${provider.senderId}`);
  if (provider.dltEntityId) parts.push('DLT added');

  return parts.length > 0 ? parts.join(' • ') : 'Provider details not completed yet';
}

function ProfileStatusPill({ complete }) {
  return (
    <span
      className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] ${
        complete
          ? 'border-emerald-200 bg-emerald-50 text-emerald-700'
          : 'border-amber-200 bg-amber-50 text-amber-700'
      }`}
    >
      {complete ? 'Complete' : 'Missing Fields'}
    </span>
  );
}

export default function Providers() {
  const { businessId } = useParams();
  const navigate = useNavigate();
  const { refreshOnboardingState } = useBusiness();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [profiles, setProfiles] = useState([]);
  const [activeProfileId, setActiveProfileId] = useState('');
  const [selectedProfileId, setSelectedProfileId] = useState('');
  const [form, setForm] = useState({
    providerName: '',
    senderId: '',
    dltEntityId: '',
    authKey: '',
  });
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [copiedProfileId, setCopiedProfileId] = useState('');
  const copyTimeoutRef = useRef(null);

  const globalSmsPath = `/${businessId}/global-sms`;

  const loadProfiles = useCallback(async () => {
    try {
      setLoading(true);
      const res = await apiClient.get(`/api/businesses/${businessId}/global-sms/profiles`);
      const fetchedProfiles = res.data?.profiles || [];
      const nextActiveProfileId = String(res.data?.activeProfileId || '');

      setProfiles(fetchedProfiles);
      setActiveProfileId(nextActiveProfileId);
      setSelectedProfileId((currentSelectedProfileId) => (
        fetchedProfiles.some((profile) => profile.id === currentSelectedProfileId)
          ? currentSelectedProfileId
          : ''
      ));
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to load provider profiles');
    } finally {
      setLoading(false);
    }
  }, [businessId]);

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

  useEffect(() => () => {
    if (copyTimeoutRef.current) {
      clearTimeout(copyTimeoutRef.current);
    }
  }, []);

  const selectedProfile = profiles.find((profile) => profile.id === selectedProfileId) || null;

  useEffect(() => {
    if (!selectedProfile) {
      setForm({
        providerName: '',
        senderId: '',
        dltEntityId: '',
        authKey: '',
      });
      return;
    }

    const provider = selectedProfile.provider || {};
    setForm({
      providerName: provider.providerName || '',
      senderId: provider.senderId || '',
      dltEntityId: provider.dltEntityId || '',
      authKey: provider.authKey || '',
    });
  }, [selectedProfile]);

  function handleChange(field, value) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  function handleSelectProfile(profileId) {
    setSelectedProfileId(profileId);
    setError('');
    setSuccess('');
  }

  function handleReturnToList() {
    setSelectedProfileId('');
    setError('');
    setSuccess('');
  }

  async function handleActivate(profile) {
    if (!profile?.id) return;

    try {
      setError('');
      setSuccess('');
      await apiClient.post(`/api/businesses/${businessId}/global-sms/profiles/${profile.id}/activate`);
      setSelectedProfileId(profile.id);
      await loadProfiles();
      await refreshOnboardingState(businessId).catch(() => null);
      setSuccess(`${profile.name} is now the active profile.`);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to activate profile');
    }
  }

  async function handleCopyCurl(profile) {
    if (!profile?.rawCurl) return;

    try {
      if (!navigator?.clipboard?.writeText) {
        throw new Error('Clipboard API unavailable');
      }

      await navigator.clipboard.writeText(profile.rawCurl);
      setCopiedProfileId(profile.id);

      if (copyTimeoutRef.current) {
        clearTimeout(copyTimeoutRef.current);
      }

      copyTimeoutRef.current = window.setTimeout(() => {
        setCopiedProfileId('');
      }, 1800);
    } catch {
      setError('Failed to copy the cURL command.');
    }
  }

  async function handleSave(event) {
    event.preventDefault();

    if (!selectedProfile?.id) return;

    setSaving(true);
    setError('');
    setSuccess('');

    if (form.senderId && !/^[A-Za-z]{6}$/.test(form.senderId)) {
      setError('DLT Sender ID must be exactly 6 alphabet characters');
      setSaving(false);
      return;
    }

    try {
      await apiClient.patch(`/api/businesses/${businessId}/global-sms/profiles/${selectedProfile.id}`, {
        provider: {
          providerName: form.providerName,
          senderId: form.senderId.toUpperCase(),
          dltEntityId: form.dltEntityId,
          authKey: form.authKey,
        },
      });

      await loadProfiles();
      await refreshOnboardingState(businessId).catch(() => null);
      setSuccess(`Provider configuration saved for ${selectedProfile.name}.`);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to save configuration');
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center">
        <div className="h-8 w-8 rounded-full border-2 border-gray-200 border-t-indigo-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-6xl space-y-6 pb-12">
      <div className="flex flex-col gap-4 border-b border-gray-200 pb-5 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-gray-800">Provider Configuration</h1>
          <p className="mt-1 text-sm font-medium text-gray-500">
            Review the provider details stored against each saved cURL profile.
          </p>
        </div>
        <button
          type="button"
          onClick={() => navigate(globalSmsPath)}
          className="inline-flex items-center justify-center rounded-lg border border-gray-200 px-4 py-2 text-sm font-semibold text-gray-700 transition hover:border-primary-blue hover:bg-white hover:text-primary-blue"
        >
          Manage cURLs
        </button>
      </div>

      {error && (
        <div className="flex items-center justify-between rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700">
          {error}
          <button type="button" onClick={() => setError('')} className="font-bold text-gray-600 hover:text-gray-700">
            &times;
          </button>
        </div>
      )}
      {success && (
        <div className="flex items-center justify-between rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700">
          {success}
          <button type="button" onClick={() => setSuccess('')} className="font-bold text-gray-600 hover:text-gray-700">
            &times;
          </button>
        </div>
      )}

      {!selectedProfile ? (
        <section className="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm">
          <div className="border-b border-gray-200 px-5 py-4">
            <div className="flex items-start justify-between gap-4">
              <div>
                <p className="text-sm font-semibold text-gray-900">Saved Profiles</p>
              </div>
              <span className="rounded-full border border-gray-200 bg-gray-50 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-gray-500">
                {profiles.length} total
              </span>
            </div>
          </div>

          {profiles.length === 0 ? (
            <div className="px-5 py-8 text-center">
              <p className="text-sm font-semibold text-gray-900">No saved profiles yet</p>
              <p className="mt-2 text-sm text-gray-500">
                Add and validate a cURL profile from Omni-channel SMS before configuring provider details here.
              </p>
              <button
                type="button"
                onClick={() => navigate(globalSmsPath)}
                className="mt-4 inline-flex items-center justify-center rounded-lg bg-primary-blue px-4 py-2 text-sm font-semibold text-white transition hover:bg-primary-dark"
              >
                Go to Omni-channel SMS
              </button>
            </div>
          ) : (
            <div className="p-3">
              <div className="space-y-3">
                {profiles.map((profile) => {
                  const isActive = profile.id === activeProfileId;
                  const complete = isProviderSetupComplete(profile);

                  return (
                    <button
                      key={profile.id}
                      type="button"
                      onClick={() => handleSelectProfile(profile.id)}
                      className="w-full rounded-xl border border-gray-200 bg-white p-4 text-left transition hover:border-primary-blue hover:bg-gray-50"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                          <p className="truncate text-sm font-semibold text-gray-900">{profile.name}</p>
                          <p className="mt-1 text-sm leading-relaxed text-gray-500">{buildProviderSummary(profile)}</p>
                        </div>
                        <div className="flex shrink-0 flex-wrap justify-end gap-2">
                          {isActive && (
                            <span className="rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary-dark">
                              Active
                            </span>
                          )}
                          <ProfileStatusPill complete={complete} />
                        </div>
                      </div>

                      <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs font-medium text-gray-500">
                        <span>Updated {formatUpdatedAt(profile.updatedAt)}</span>
                        {profile.provider?.senderId && <span>Sender {profile.provider.senderId}</span>}
                        {profile.provider?.dltEntityId && <span>DLT ready</span>}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </section>
      ) : (
        <section className="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm">
          <div className="border-b border-gray-200 px-6 py-5">
            <div className="flex flex-col gap-4">
              <button
                type="button"
                onClick={handleReturnToList}
                className="inline-flex w-fit items-center gap-2 text-sm font-semibold text-gray-500 transition hover:text-primary-blue"
              >
                <span>Saved Profiles</span>
                <span className="text-gray-300">/</span>
                <span className="text-gray-900">{selectedProfile.name}</span>
              </button>

              <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <h2 className="text-xl font-semibold tracking-tight text-gray-900">{selectedProfile.name}</h2>
                    {selectedProfile.id === activeProfileId && (
                      <span className="rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary-dark">
                        Active profile
                      </span>
                    )}
                    <ProfileStatusPill complete={isProviderSetupComplete(selectedProfile)} />
                  </div>
                  <p className="mt-2 text-sm text-gray-500">
                    Review the exact saved request, then update the provider fields tied to this profile.
                  </p>
                </div>

                <div className="flex flex-wrap items-center gap-2">
                  {selectedProfile.id !== activeProfileId && (
                    <button
                      type="button"
                      onClick={() => handleActivate(selectedProfile)}
                      className="rounded-lg bg-primary-blue px-4 py-2 text-sm font-semibold text-white transition hover:bg-primary-dark"
                    >
                      Set Active
                    </button>
                  )}
                  <button
                    type="button"
                    onClick={() => handleCopyCurl(selectedProfile)}
                    className="rounded-lg border border-gray-200 px-4 py-2 text-sm font-semibold text-gray-700 transition hover:border-primary-blue hover:bg-gray-50 hover:text-primary-blue"
                  >
                    {copiedProfileId === selectedProfile.id ? 'Copied' : 'Copy cURL'}
                  </button>
                  <button
                    type="button"
                    onClick={() => navigate(`${globalSmsPath}?editProfile=${encodeURIComponent(selectedProfile.id)}`)}
                    className="rounded-lg border border-gray-200 px-4 py-2 text-sm font-semibold text-gray-700 transition hover:border-primary-blue hover:bg-gray-50 hover:text-primary-blue"
                  >
                    Edit cURL
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="space-y-6 px-6 py-6">
            <div className="overflow-hidden rounded-2xl border border-gray-200 bg-gray-950">
              <div className="flex items-center justify-between gap-4 border-b border-gray-800 px-4 py-3">
                <div>
                  <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-gray-400">Preview</p>
                </div>
                <span className="rounded-full border border-gray-700 bg-gray-900 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-gray-300">
                  Updated {formatUpdatedAt(selectedProfile.updatedAt)}
                </span>
              </div>
              <pre className="max-h-72 overflow-y-auto overscroll-contain whitespace-pre-wrap break-all px-4 py-4 text-xs leading-relaxed text-gray-100">
                <code>{selectedProfile.rawCurl}</code>
              </pre>
            </div>

            <div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_260px]">
              <form onSubmit={handleSave} className="overflow-hidden rounded-2xl border border-gray-200 bg-white">
                <div className="border-b border-gray-200 px-5 py-4">
                  <p className="text-sm font-semibold text-gray-900">Provider Details</p>
                  <p className="mt-1 text-sm text-gray-500">
                    These fields are stored against this profile and are used during template publishing.
                  </p>
                </div>

                <div className="space-y-5 px-5 py-5">
                  <div>
                    <label className={`mb-1.5 block text-sm font-semibold tracking-wide ${!form.providerName ? 'text-error-text' : 'text-text-primary'}`}>
                      Provider Name {!form.providerName && <span className="text-error-text">*</span>}
                    </label>
                    <input
                      type="text"
                      value={form.providerName}
                      onChange={(event) => handleChange('providerName', event.target.value)}
                      className={`w-full rounded-lg border px-4 py-2 text-sm font-medium text-text-primary placeholder-placeholder-bg transition focus:border-transparent focus:outline-none focus:ring-2 ${!form.providerName ? 'border-error-text focus:ring-error-text' : 'border-border-main focus:ring-primary-blue'} bg-surface-white`}
                      placeholder="e.g. MSG91, Gupshup"
                    />
                  </div>

                  <div className="grid gap-5 sm:grid-cols-2">
                    <div>
                      <label className={`mb-1.5 block text-sm font-semibold tracking-wide ${!form.senderId ? 'text-error-text' : 'text-text-primary'}`}>
                        DLT Sender ID {!form.senderId && <span className="text-error-text">*</span>}
                      </label>
                      <input
                        type="text"
                        value={form.senderId}
                        onChange={(event) => handleChange('senderId', event.target.value.toUpperCase())}
                        maxLength={6}
                        className={`w-full rounded-lg border px-4 py-2 font-mono text-sm uppercase tracking-widest text-text-primary placeholder-placeholder-bg transition focus:border-transparent focus:outline-none focus:ring-2 ${!form.senderId ? 'border-error-text focus:ring-error-text' : 'border-border-main focus:ring-primary-blue'} bg-surface-white`}
                        placeholder="6 CHARS"
                      />
                      <p className="mt-2 text-xs font-medium text-gray-500">Exactly 6 alphabetic characters.</p>
                    </div>

                    <div>
                      <label className={`mb-1.5 block text-sm font-semibold tracking-wide ${!form.dltEntityId ? 'text-error-text' : 'text-text-primary'}`}>
                        DLT Entity ID {!form.dltEntityId && <span className="text-error-text">*</span>}
                      </label>
                      <input
                        type="text"
                        value={form.dltEntityId}
                        onChange={(event) => handleChange('dltEntityId', event.target.value)}
                        className={`w-full rounded-lg border px-4 py-2 font-mono text-sm text-text-primary placeholder-placeholder-bg transition focus:border-transparent focus:outline-none focus:ring-2 ${!form.dltEntityId ? 'border-error-text focus:ring-error-text' : 'border-border-main focus:ring-primary-blue'} bg-surface-white`}
                        placeholder="19-digit DLT PE ID"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="mb-1.5 block text-sm font-semibold tracking-wide text-text-primary">
                      API Auth Key <span className="text-xs font-normal text-text-muted">(Optional)</span>
                    </label>
                    <input
                      type="password"
                      value={form.authKey}
                      onChange={(event) => handleChange('authKey', event.target.value)}
                      className="w-full rounded-lg border border-border-main bg-surface-white px-4 py-2 font-mono text-sm text-text-primary placeholder-placeholder-bg transition focus:border-transparent focus:outline-none focus:ring-2 focus:ring-primary-blue"
                      placeholder="Authorization key for your SMS provider"
                    />
                    <p className="mt-2 text-xs font-medium text-gray-500">
                      Used as the Authorization header in your SMS requests.
                    </p>
                  </div>
                </div>

                <div className="flex justify-end border-t border-gray-200 bg-white px-5 py-4">
                  <button
                    type="submit"
                    disabled={saving}
                    className="flex items-center justify-center gap-2 rounded-lg bg-primary-blue px-6 py-2 text-sm font-semibold text-white transition hover:bg-primary-dark disabled:opacity-50"
                  >
                    {saving ? (
                      <>
                        <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                        Saving…
                      </>
                    ) : 'Save Configuration'}
                  </button>
                </div>
              </form>

              <aside className="rounded-2xl border border-gray-200 bg-gray-50 p-5">
                <p className="text-sm font-semibold text-gray-900">Current Status</p>
                <ul className="mt-4 space-y-3 text-sm">
                  <li className="rounded-xl border border-gray-200 bg-white px-4 py-3">
                    <p className="text-xs font-semibold uppercase tracking-[0.14em] text-gray-400">Profile State</p>
                    <p className="mt-2 font-medium text-gray-900">
                      {selectedProfile.id === activeProfileId ? 'Currently active for generation' : 'Inactive profile'}
                    </p>
                  </li>
                  <li className="rounded-xl border border-gray-200 bg-white px-4 py-3">
                    <p className="text-xs font-semibold uppercase tracking-[0.14em] text-gray-400">Provider Setup</p>
                    <p className="mt-2 font-medium text-gray-900">
                      {isProviderSetupComplete(selectedProfile)
                        ? 'All mandatory provider fields are complete.'
                        : getMissingProviderFields(selectedProfile).join(', ')}
                    </p>
                  </li>
                  <li className="rounded-xl border border-gray-200 bg-white px-4 py-3">
                    <p className="text-xs font-semibold uppercase tracking-[0.14em] text-gray-400">Auth Key</p>
                    <p className="mt-2 font-medium text-gray-900">
                      {selectedProfile.provider?.authKey ? 'Saved on this profile' : 'Not added'}
                    </p>
                  </li>
                </ul>
              </aside>
            </div>
          </div>
        </section>
      )}
    </div>
  );
}
