import { useEffect, useState } from 'react'
import { Database, Copy, RefreshCw, Link as LinkIcon, TestTube2, Save, AlertTriangle, Calendar, CheckCircle2, XCircle, ExternalLink, Loader2 } from 'lucide-react'
import { t } from '@/lib/i18n'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { apiClient } from '@/api/client'

type WebhookEvents = {
  lead_created: boolean
  conversation_started: boolean
  meeting_booked: boolean
}

type CrmSettingsResponse = {
  // Backward compatibility with older endpoint response shape
  api_key?: string
  has_key?: boolean
  export_api_key?: string
  export_has_key?: boolean
  webhook_url?: string
  webhook_api_key?: string
  webhook_enabled?: boolean
  webhook_events?: Partial<WebhookEvents>
}

type GoogleStatus = {
  configured: boolean
  connected: boolean
  email: string | null
  using_constants: boolean
}


export function Integrations() {
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [saveMessage, setSaveMessage] = useState<string | null>(null)
  const [isDataLoaded, setIsDataLoaded] = useState(false)

  // Export API key (read-only, generated)
  const [exportApiKey, setExportApiKey] = useState('')
  const [exportHasKey, setExportHasKey] = useState(false)
  const [isGeneratingExportKey, setIsGeneratingExportKey] = useState(false)
  const [exportCopied, setExportCopied] = useState(false)

  // Webhook configuration
  const [webhookEnabled, setWebhookEnabled] = useState(false)
  const [webhookUrl, setWebhookUrl] = useState('')
  const [webhookApiKey, setWebhookApiKey] = useState('')
  const [events, setEvents] = useState<WebhookEvents>({
    lead_created: true,
    conversation_started: true,
    meeting_booked: true,
  })
  const [isTestingWebhook, setIsTestingWebhook] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null)

  // Google Calendar
  const [googleStatus, setGoogleStatus] = useState<GoogleStatus>({
    configured: false,
    connected: false,
    email: null,
    using_constants: false,
  })
  const [isGoogleLoading, setIsGoogleLoading] = useState(false)
  const [googleMessage, setGoogleMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  // Load Google Calendar status
  const loadGoogleStatus = async () => {
    try {
      const statusRes = await apiClient.get<{ data: GoogleStatus }>('google/status')
      setGoogleStatus(statusRes.data || { configured: false, connected: false, email: null, using_constants: true })
    } catch (e) {
      console.error('Failed to load Google status', e)
    }
  }

  useEffect(() => {
    const load = async () => {
      try {
        const response = await apiClient.get<{ data: CrmSettingsResponse }>('settings/crm')
        const data = response.data || {}

        setExportApiKey(data.export_api_key || data.api_key || '')
        setExportHasKey(!!(data.export_has_key ?? data.has_key))

        setWebhookEnabled(!!data.webhook_enabled)
        setWebhookUrl(data.webhook_url || '')
        setWebhookApiKey(data.webhook_api_key || '')
        setEvents((prev) => ({
          ...prev,
          ...(data.webhook_events || {}),
        }))
        setIsDataLoaded(true)
      } catch (e) {
        console.error('Failed to load CRM integrations settings', e)
        setIsDataLoaded(true)
      } finally {
        setIsLoading(false)
      }
    }

    load()
    loadGoogleStatus()

    // Check for Google OAuth callback params in URL
    const params = new URLSearchParams(window.location.search)
    if (params.get('google_connected') === '1') {
      setGoogleMessage({ type: 'success', text: t('Google Calendar connected successfully!') })
      // Clean URL
      const url = new URL(window.location.href)
      url.searchParams.delete('google_connected')
      window.history.replaceState({}, '', url.toString())
      // Refresh status
      loadGoogleStatus()
    } else if (params.get('google_error')) {
      const errorCode = params.get('google_error') || ''
      const errorMap: Record<string, string> = {
        access_denied: t('Access denied. Please approve the permissions.'),
        invalid_state: t('Authentication error. Please try again.'),
        no_code: t('Authentication code not received from Google.'),
        callback_failed: t('Error processing response from Google.'),
      }
      const knownMsg = Object.entries(errorMap).find(([key]) => errorCode.startsWith(key))?.[1]
      setGoogleMessage({ type: 'error', text: knownMsg ? `${knownMsg} (${errorCode})` : `${t('Error:')} ${errorCode}` })
      // Clean URL
      const url = new URL(window.location.href)
      url.searchParams.delete('google_error')
      window.history.replaceState({}, '', url.toString())
    }
  }, [])

  // Google Calendar handlers
  const handleGoogleConnect = async () => {
    setIsGoogleLoading(true)
    setGoogleMessage(null)
    try {
      const res = await apiClient.get<{ data: { url: string } }>('google/auth-url')
      if (res.data?.url) {
        window.location.href = res.data.url
      } else {
        setGoogleMessage({ type: 'error', text: t('Unable to create authorization link') })
      }
    } catch (e) {
      console.error('Failed to get Google auth URL', e)
      setGoogleMessage({ type: 'error', text: t('Error receiving authorization link. Please try again later.') })
    } finally {
      setIsGoogleLoading(false)
    }
  }

  const handleGoogleDisconnect = async () => {
    if (!window.confirm(t('Disconnect Google account? Existing meetings will not be deleted.'))) return
    setIsGoogleLoading(true)
    try {
      await apiClient.post('google/disconnect')
      setGoogleMessage({ type: 'success', text: t('Google Calendar disconnected successfully') })
      await loadGoogleStatus()
      setTimeout(() => setGoogleMessage(null), 3000)
    } catch (e) {
      console.error('Failed to disconnect Google', e)
      setGoogleMessage({ type: 'error', text: t('Error disconnecting') })
    } finally {
      setIsGoogleLoading(false)
    }
  }

  const handleGenerateExportKey = async () => {
    if (exportHasKey && !window.confirm(t('Generating a new key will invalidate the existing key. Continue?'))) {
      return
    }

    setIsGeneratingExportKey(true)
    try {
      const response = await apiClient.post<{ data: { key: string } }>('settings/crm/generate-key')
      if (response.data?.key) {
        setExportApiKey(response.data.key)
        setExportHasKey(true)
      }
    } catch (e) {
      console.error('Failed to generate export key', e)
      alert(t('Error generating API key'))
    } finally {
      setIsGeneratingExportKey(false)
    }
  }

  const handleCopyExportKey = async () => {
    if (!exportApiKey || exportApiKey.includes('...')) {
      alert(t('Export key is hidden for security. Generate a new key to copy it.'))
      return
    }
    try {
      await navigator.clipboard.writeText(exportApiKey)
      setExportCopied(true)
      setTimeout(() => setExportCopied(false), 2000)
    } catch {
      alert(t('Failed to copy to clipboard'))
    }
  }

  const handleSaveWebhook = async () => {
    setIsSaving(true)
    setSaveMessage(null)
    try {
      const payload = {
        webhook_enabled: webhookEnabled,
        webhook_url: webhookUrl,
        webhook_api_key: webhookApiKey,
        webhook_events: events,
      }

      const response = await apiClient.post<{ data: { message: string } }>('settings/crm/webhook', payload)
      setSaveMessage(response.data?.message || t('Saved successfully'))
      setTimeout(() => setSaveMessage(null), 2500)
      setOriginalData()
    } catch (e: any) {
      console.error('Failed to save webhook settings', e)
      setSaveMessage(e?.message || t('Error saving'))
      setTimeout(() => setSaveMessage(null), 3500)
    } finally {
      setIsSaving(false)
    }
  }

  // Unsaved changes detection for webhook settings
  const {
    hasUnsavedChanges,
    setOriginalData,
    showModal: showUnsavedModal,
    saveError,
    modalActions,
  } = useUnsavedChanges({
    currentData: { webhookEnabled, webhookUrl, webhookApiKey, events },
    onSave: async () => { await handleSaveWebhook() },
    onDiscard: (original) => {
      setWebhookEnabled(original.webhookEnabled)
      setWebhookUrl(original.webhookUrl)
      setWebhookApiKey(original.webhookApiKey)
      setEvents(original.events)
    },
    isLoaded: isDataLoaded,
  })

  const handleTestWebhook = async () => {
    setIsTestingWebhook(true)
    setTestResult(null)
    try {
      const response = await apiClient.post<{ data: { success: boolean; message: string } }>('settings/crm/test-webhook', {})
      setTestResult({
        success: !!response.data?.success,
        message: response.data?.message || (response.data?.success ? t('Test succeeded') : t('Test failed')),
      })
    } catch (e: any) {
      setTestResult({ success: false, message: e?.message || t('Error testing webhook') })
    } finally {
      setIsTestingWebhook(false)
    }
  }

  if (isLoading) {
    return (
      <Card>
        <CardContent className="py-10 text-center text-gray-500">{t('Loading...')}</CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-6 animate-fade-in" data-wizard-id="integrations-content">
      {/* Unsaved Changes Modal */}
      <UnsavedChangesModal
        isOpen={showUnsavedModal}
        onCancel={modalActions.onCancel}
        onDiscard={modalActions.onDiscard}
        onSave={modalActions.onSave}
        onSaveAlways={modalActions.onSaveAlways}
        isSaving={isSaving}
        errorMessage={saveError}
      />

      {/* Unsaved changes indicator */}
      {hasUnsavedChanges && (
        <div className="fixed bottom-4 left-4 bg-amber-100 text-amber-800 px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 text-sm z-40">
          <AlertTriangle className="w-4 h-4" />
          {t('You have unsaved changes')}
        </div>
      )}

      <PageHeader title={t('Integrations')} subtitle={t('Connect to CRM, Zapier, Make, n8n and more')} />

      {/* Google Calendar */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="w-5 h-5" />
            Google Calendar
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-5">
          {/* Status indicator */}
          <div className="flex items-center gap-3">
            {googleStatus.connected ? (
              <div className="flex items-center gap-2 bg-green-50 text-green-800 px-4 py-2 rounded-lg text-sm">
                <CheckCircle2 className="w-4 h-4" />
                <span>{t('Connected')}</span>
                {googleStatus.email && <span className="font-medium">({googleStatus.email})</span>}
              </div>
            ) : (
              <div className="flex items-center gap-2 bg-amber-50 text-amber-800 px-4 py-2 rounded-lg text-sm">
                <AlertTriangle className="w-4 h-4" />
                <span>{t('Not connected — connect your Google account for calendar sync')}</span>
              </div>
            )}
          </div>

          {/* Feedback message */}
          {googleMessage && (
            <div className={`rounded-lg p-3 text-sm ${
              googleMessage.type === 'success' ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'
            }`}>
              {googleMessage.text}
            </div>
          )}

          {/* Connect/Disconnect buttons */}
          <div className="flex flex-wrap gap-2 items-center">
            {googleStatus.connected ? (
              <button
                onClick={handleGoogleDisconnect}
                disabled={isGoogleLoading}
                className="flex items-center gap-2 px-4 py-2 bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 rounded-lg transition-all disabled:opacity-50"
              >
                {isGoogleLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <XCircle className="w-4 h-4" />}
                {t('Disconnect Google Calendar')}
              </button>
            ) : (
              <button
                onClick={handleGoogleConnect}
                disabled={isGoogleLoading}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-all disabled:opacity-50"
              >
                {isGoogleLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ExternalLink className="w-4 h-4" />}
                {t('Connect Google Account')}
              </button>
            )}
          </div>

          {/* One-way sync clarification */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
            <p className="font-medium mb-1">{t('One-way sync only')}</p>
            <p>
              {t('Meetings scheduled through the chatbot are automatically transferred to your Google Calendar.')}
              {' '}
              {t('Meeting availability is determined by local site meetings only — without considering Google Calendar events.')}
            </p>
          </div>

          {/* Features */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div className="bg-white border border-gray-200 rounded-lg p-3 text-center">
              <Calendar className="w-6 h-6 text-blue-500 mx-auto mb-1" />
              <p className="text-sm font-medium text-gray-900">{t('Create Events')}</p>
              <p className="text-xs text-gray-500">{t('Meetings are automatically saved to calendar')}</p>
            </div>
            <div className="bg-white border border-gray-200 rounded-lg p-3 text-center">
              <LinkIcon className="w-6 h-6 text-green-500 mx-auto mb-1" />
              <p className="text-sm font-medium text-gray-900">Google Meet</p>
              <p className="text-xs text-gray-500">{t('Automatic meeting link')}</p>
            </div>
            <div className="bg-white border border-gray-200 rounded-lg p-3 text-center">
              <ExternalLink className="w-6 h-6 text-purple-500 mx-auto mb-1" />
              <p className="text-sm font-medium text-gray-900">{t('Export Meetings')}</p>
              <p className="text-xs text-gray-500">{t('Meetings from the site are transferred to Google Calendar')}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Webhook configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <LinkIcon className="w-5 h-5" />
            {t('Webhook for Sending Events')}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-5">
          <div className="flex items-center gap-3">
            <input
              id="bb-webhook-enabled"
              type="checkbox"
              checked={webhookEnabled}
              onChange={(e) => setWebhookEnabled(e.target.checked)}
              className="h-4 w-4"
            />
            <label htmlFor="bb-webhook-enabled" className="text-sm text-gray-800">
              {t('Enable automatic sending to webhook')}
            </label>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">{t('Webhook URL')}</label>
              <input
                type="url"
                value={webhookUrl}
                onChange={(e) => setWebhookUrl(e.target.value)}
                placeholder="https://hooks.zapier.com/hooks/catch/..."
                className="w-full text-sm bg-white border border-gray-300 rounded-lg px-3 py-2"
              />
              <p className="text-xs text-gray-500 mt-1">{t('Supported: Zapier / Make / n8n / any system that accepts POST JSON')}</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">{t('Security Key (Optional)')}</label>
              <input
                type="text"
                value={webhookApiKey}
                onChange={(e) => setWebhookApiKey(e.target.value)}
                placeholder={t('e.g.: secret_123')}
                className="w-full font-mono text-sm bg-white border border-gray-300 rounded-lg px-3 py-2"
              />
              <p className="text-xs text-gray-500 mt-1">{t('Sent in headers: Authorization Bearer + X-API-Key')}</p>
            </div>
          </div>

          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-medium text-gray-900 mb-2">{t('Select Events to Send')}</h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={events.lead_created}
                  onChange={(e) => setEvents((prev) => ({ ...prev, lead_created: e.target.checked }))}
                  className="h-4 w-4"
                />
                {t('New Leads')}
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={events.conversation_started}
                  onChange={(e) => setEvents((prev) => ({ ...prev, conversation_started: e.target.checked }))}
                  className="h-4 w-4"
                />
                {t('Conversation Started')}
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={events.meeting_booked}
                  onChange={(e) => setEvents((prev) => ({ ...prev, meeting_booked: e.target.checked }))}
                  className="h-4 w-4"
                />
                {t('Meeting Booked')}
              </label>
            </div>
          </div>

          <div className="flex flex-wrap gap-2 items-center">
            <button
              onClick={handleSaveWebhook}
              disabled={isSaving}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                hasUnsavedChanges
                  ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                  : 'bg-primary-600 hover:bg-primary-700'
              } text-white`}
            >
              <Save className="w-4 h-4" />
              {isSaving ? t('Saving...') : hasUnsavedChanges ? t('Save Changes') : t('Save')}
            </button>
            <Button variant="outline" onClick={handleTestWebhook} disabled={isTestingWebhook}>
              <TestTube2 className={`w-4 h-4 me-2 ${isTestingWebhook ? 'animate-spin' : ''}`} />
              {t('Test Webhook')}
            </Button>

            {saveMessage && (
              <span className="text-sm text-gray-700 ms-2">{saveMessage}</span>
            )}
          </div>

          {testResult && (
            <div className={`rounded-lg p-3 text-sm ${testResult.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'}`}>
              {testResult.message}
            </div>
          )}

          <div className="text-sm text-gray-600">
            <h4 className="font-medium text-gray-900 mb-1">{t('Payload Structure (JSON)')}</h4>
            <ul className="list-disc list-inside space-y-1">
              <li><span className="font-mono">event</span>{': '}{t('Event type (e.g. lead_created)')}</li>
              <li><span className="font-mono">timestamp</span>{': '}{t('Time (UTC)')}</li>
              <li><span className="font-mono">site_url</span>{': '}{t('Site URL')}</li>
              <li><span className="font-mono">data</span>{': '}{t('Lead/conversation/meeting data')}</li>
            </ul>
          </div>
        </CardContent>
      </Card>

      {/* CRM Export API Key */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Database className="w-5 h-5" />
            {t('Export Data to CRM (API Key)')}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-gray-600">{t('Read-only key for pulling data (leads/conversations/meetings).')}</p>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">{t('API Key')}</label>
            <div className="flex gap-2">
              <input
                type="text"
                value={exportApiKey}
                readOnly
                className="flex-1 font-mono text-sm bg-gray-50 border border-gray-300 rounded-lg px-3 py-2"
                placeholder={t('Not yet generated')}
              />
              {exportHasKey && (
                <Button variant="outline" onClick={handleCopyExportKey} className="flex-shrink-0">
                  <Copy className="w-4 h-4 me-1" />
                  {exportCopied ? t('Copied!') : t('Copy')}
                </Button>
              )}
              <Button
                variant="outline"
                onClick={handleGenerateExportKey}
                disabled={isGeneratingExportKey}
                className="flex-shrink-0"
              >
                <RefreshCw className={`w-4 h-4 me-1 ${isGeneratingExportKey ? 'animate-spin' : ''}`} />
                {exportHasKey ? t('Generate New') : t('Generate Key')}
              </Button>
            </div>
            <p className="text-xs text-gray-500 mt-1">
              {t('Send the Key in the header:')} <code className="bg-gray-100 px-1 rounded">X-BoostBot-API-Key</code>
            </p>
          </div>

          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-medium text-gray-900 mb-2">{t('Available Endpoints')}</h4>
            <ul className="text-sm font-mono space-y-1 text-gray-700">
              <li>GET /wp-json/boostbot/v1/crm/leads</li>
              <li>GET /wp-json/boostbot/v1/crm/leads/{'{id}'}</li>
              <li>GET /wp-json/boostbot/v1/crm/conversations</li>
              <li>GET /wp-json/boostbot/v1/crm/meetings</li>
              <li>GET /wp-json/boostbot/v1/crm/meetings/{'{id}'}</li>
            </ul>
          </div>
        </CardContent>
      </Card>

      {/* In-page documentation */}
      <Card>
        <CardHeader>
          <CardTitle>{t('Documentation and Implementation')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 text-sm text-gray-700">
          <p className="text-gray-600">
            {t('You can connect any automation/CRM system using Webhook (push) or API Key (pull).')}
          </p>
          <div className="space-y-2">
            <h4 className="font-medium text-gray-900">{t('Quick Setup (Zapier/Make/n8n)')}</h4>
            <ol className="list-decimal list-inside space-y-1">
              <li>{t('Create a "Catch Hook / Webhook" trigger in your system')}</li>
              <li>{t('Paste the webhook URL here')}</li>
              <li>{t('Select the desired events and save')}</li>
              <li>{t('Click "Test Webhook" to send a test event')}</li>
              <li>{t('Build Actions that receive the JSON and map to fields in your system')}</li>
            </ol>
          </div>
          <div className="bg-blue-50 rounded-lg p-4">
            <p className="font-medium text-blue-900 mb-1">{t('Tip')}</p>
            <p className="text-blue-800">
              {t('If you want us to send a custom header/signature (HMAC) for verification, we can add this in the next phase.')}
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

