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

const DESKTOP_SPLIT_QUERY = '(min-width: 1100px)';
const DEFAULT_LIST_PANE_WIDTH = 340;
const MIN_LIST_PANE_WIDTH = 280;
const MAX_LIST_PANE_WIDTH = 420;
const MIN_DETAIL_PANE_WIDTH = 440;

function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

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 [isDesktopSplit, setIsDesktopSplit] = useState(false);
  const [listPaneWidth, setListPaneWidth] = useState(DEFAULT_LIST_PANE_WIDTH);
  const layoutRef = useRef(null);
  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(() => {
    const mediaQuery = window.matchMedia(DESKTOP_SPLIT_QUERY);
    const syncLayoutMode = (event) => setIsDesktopSplit(event.matches);

    setIsDesktopSplit(mediaQuery.matches);

    if (typeof mediaQuery.addEventListener === 'function') {
      mediaQuery.addEventListener('change', syncLayoutMode);
      return () => mediaQuery.removeEventListener('change', syncLayoutMode);
    }

    mediaQuery.addListener(syncLayoutMode);
    return () => mediaQuery.removeListener(syncLayoutMode);
  }, []);

  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 handleResizeStart(event) {
    if (!isDesktopSplit) return;

    event.preventDefault();
    const containerBounds = layoutRef.current?.getBoundingClientRect();
    if (!containerBounds) return;

    const maxAllowedWidth = clamp(
      containerBounds.width - MIN_DETAIL_PANE_WIDTH,
      MIN_LIST_PANE_WIDTH,
      MAX_LIST_PANE_WIDTH,
    );

    function handlePointerMove(moveEvent) {
      const nextWidth = clamp(
        moveEvent.clientX - containerBounds.left,
        MIN_LIST_PANE_WIDTH,
        maxAllowedWidth,
      );
      setListPaneWidth(nextWidth);
    }

    function handlePointerUp() {
      document.body.style.userSelect = '';
      window.removeEventListener('mousemove', handlePointerMove);
      window.removeEventListener('mouseup', handlePointerUp);
    }

    document.body.style.userSelect = 'none';
    window.addEventListener('mousemove', handlePointerMove);
    window.addEventListener('mouseup', handlePointerUp);
  }

  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 items-center justify-center h-64">
        <div className="w-8 h-8 border-2 border-gray-200 border-t-indigo-600 rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-7xl 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">
            Pick a saved profile to review its complete request and manage the provider details stored against it.
          </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="px-4 py-2 rounded-md bg-white border border-gray-200 text-gray-700 font-medium text-sm flex items-center justify-between">
          {error}
          <button onClick={() => setError('')} className="text-gray-600 hover:text-gray-700 font-bold">&times;</button>
        </div>
      )}
      {success && (
        <div className="px-4 py-2 rounded-md bg-white border border-gray-200 text-gray-700 font-medium text-sm flex items-center justify-between">
          {success}
          <button onClick={() => setSuccess('')} className="text-gray-600 hover:text-gray-700 font-bold">&times;</button>
        </div>
      )}

      <div
        ref={layoutRef}
        className={`grid gap-4 ${isDesktopSplit ? 'items-start' : ''}`}
        style={isDesktopSplit ? { gridTemplateColumns: `${listPaneWidth}px 12px minmax(0, 1fr)` } : undefined}
      >
        <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="max-h-[70vh] overflow-y-auto overscroll-contain p-3">
              <div className="space-y-3">
                {profiles.map((profile) => {
                  const isActive = profile.id === activeProfileId;
                  const isSelected = profile.id === selectedProfileId;
                  const complete = isProviderSetupComplete(profile);

                  return (
                    <button
                      key={profile.id}
                      type="button"
                      onClick={() => handleSelectProfile(profile.id)}
                      className={`w-full rounded-xl border p-4 text-left transition ${isSelected
                        ? 'border-primary-blue bg-indigo-50/40 shadow-sm'
                        : 'border-gray-200 bg-white 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 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>

        {isDesktopSplit && (
          <div className="hidden self-stretch lg:flex items-stretch justify-center">
            <button
              type="button"
              onMouseDown={handleResizeStart}
              className="group relative flex h-full w-3 cursor-col-resize items-stretch justify-center bg-transparent"
              aria-label="Resize provider profile list"
            >
              <span className="pointer-events-none absolute inset-y-2 left-1/2 w-[0.5px] -translate-x-1/2 rounded-full bg-gray-300 transition group-hover:bg-primary-blue" />
            </button>
          </div>
        )}

        <section className="min-w-0 overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm">
          {!selectedProfile ? (
            <div className="flex min-h-[520px] items-center justify-center px-6 py-10 text-center">
              <div className="max-w-md">
                <p className="text-sm font-semibold uppercase tracking-[0.18em] text-gray-400">Select a profile</p>
                <h2 className="mt-3 text-2xl font-semibold tracking-tight text-gray-900">Choose a saved profile to review</h2>
                <p className="mt-3 text-sm leading-relaxed text-gray-500">
                  The selected profile will open here with a complete cURL preview, provider details, and activation controls.
                </p>
              </div>
            </div>
          ) : (
            <>
              <div className="border-b border-gray-200 px-6 py-5">
                <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 className="space-y-6 px-6 py-6">
                <div className="rounded-2xl border border-gray-200 bg-gray-950 overflow-hidden">
                  <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="rounded-2xl border border-gray-200 bg-white overflow-hidden">
                    <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={`block text-sm font-semibold mb-1.5 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 px-4 py-2 rounded-lg bg-surface-white border ${!form.providerName ? 'border-error-text focus:ring-error-text' : 'border-border-main focus:ring-primary-blue'} text-text-primary placeholder-placeholder-bg font-medium focus:outline-none focus:ring-2 focus:border-transparent transition text-sm`}
                          placeholder="e.g. MSG91, Gupshup"
                        />
                      </div>

                      <div className="grid gap-5 sm:grid-cols-2">
                        <div>
                          <label className={`block text-sm font-semibold mb-1.5 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 px-4 py-2 rounded-lg bg-surface-white border ${!form.senderId ? 'border-error-text focus:ring-error-text' : 'border-border-main focus:ring-primary-blue'} text-text-primary font-mono tracking-widest placeholder-placeholder-bg focus:outline-none focus:ring-2 focus:border-transparent transition text-sm uppercase`}
                            placeholder="6 CHARS"
                          />
                          <p className="mt-2 text-xs font-medium text-gray-500">Exactly 6 alphabetic characters.</p>
                        </div>

                        <div>
                          <label className={`block text-sm font-semibold mb-1.5 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 px-4 py-2 rounded-lg bg-surface-white border ${!form.dltEntityId ? 'border-error-text focus:ring-error-text' : 'border-border-main focus:ring-primary-blue'} text-text-primary font-mono placeholder-placeholder-bg focus:outline-none focus:ring-2 focus:border-transparent transition text-sm`}
                            placeholder="19-digit DLT PE ID"
                          />
                        </div>
                      </div>

                      <div>
                        <label className="block text-sm font-semibold text-text-primary mb-1.5 tracking-wide">
                          API Auth Key <span className="text-text-muted font-normal text-xs">(Optional)</span>
                        </label>
                        <input
                          type="password"
                          value={form.authKey}
                          onChange={(event) => handleChange('authKey', event.target.value)}
                          className="w-full px-4 py-2 rounded-lg bg-surface-white border border-border-main text-text-primary font-mono placeholder-placeholder-bg focus:outline-none focus:ring-2 focus:ring-primary-blue focus:border-transparent transition text-sm"
                          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="px-6 py-2 rounded-lg bg-primary-blue hover:bg-primary-dark text-white font-semibold text-sm transition disabled:opacity-50 flex items-center justify-center gap-2"
                      >
                        {saving ? <><span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> 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>
    </div>
  );
}
