import { useState, useEffect } from 'react';
import api from '../lib/api';
import {
  Save,
  AlertCircle,
  Database,
  CheckCircle2,
  Link2,
  ShieldAlert,
  Calendar,
  PhoneForwarded,
  Download,
  Zap,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface CrmSettingsResponse {
  provider: string;
  webhookUrl: string;
  apiKeyMasked: string;
  calendarSyncEnabled?: boolean;
  googleCalendarEmail?: string;
  outlookCalendarEmail?: string;
  sipTrunkUri?: string;
  forwardingPhoneNumber?: string;
  isConnected: boolean;
  lastTestedAt?: string;
}

const INTEGRATION_CARDS = [
  {
    id: 'google_calendar',
    name: 'Google Calendar',
    category: 'Real-Time Booking & .ics Invites',
    desc: 'Sync in-call booked appointments to Google Calendar and download live iCalendar (.ics) feeds.',
    badge: 'Native',
  },
  {
    id: 'outlook_calendar',
    name: 'Microsoft Outlook 365',
    category: 'Calendar & Exchange Sync',
    desc: 'Sync booked consultations with Microsoft 365 / Exchange calendars and generate Outlook invites.',
    badge: 'Native',
  },
  {
    id: 'hubspot',
    name: 'HubSpot CRM',
    category: 'Contacts, Deals & Call Notes',
    desc: 'Automatically push caller contacts and post-call AI summaries via HubSpot v3 API & Webhooks.',
    badge: 'Native',
  },
  {
    id: 'salesforce',
    name: 'Salesforce & Zoho',
    category: 'Enterprise CRM Sync',
    desc: 'Deliver structured lead intake, sentiment scores, and call outcome tags to Salesforce or Zoho.',
    badge: 'Native',
  },
  {
    id: 'zapier',
    name: 'Zapier / Make Webhooks',
    category: '5,000+ App Automations',
    desc: 'Dispatch HMAC-SHA256 signed JSON call events with exponential backoff retry to Zapier or Make.',
    badge: 'Native',
  },
  {
    id: 'twilio_sip',
    name: 'Twilio & BYO SIP Trunk',
    category: 'PSTN & *72 Call Forwarding',
    desc: 'Configure your inbound Twilio E.164 line, custom SIP trunk URI, or *72 / GSM call forwarding.',
    badge: 'Native',
  },
];

const CrmSettings = () => {
  const [crmType, setCrmType] = useState('hubspot');
  const [apiKey, setApiKey] = useState('');
  const [webhookUrl, setWebhookUrl] = useState('');
  const [apiKeyMasked, setApiKeyMasked] = useState('');
  const [googleCalendarEmail, setGoogleCalendarEmail] = useState('');
  const [outlookCalendarEmail, setOutlookCalendarEmail] = useState('');
  const [sipTrunkUri, setSipTrunkUri] = useState('');
  const [forwardingPhoneNumber, setForwardingPhoneNumber] = useState('+18005550199');
  const [calendarSyncEnabled, setCalendarSyncEnabled] = useState(true);
  const [loading, setLoading] = useState(false);
  const [testing, setTesting] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [status, setStatus] = useState<'disconnected' | 'connected' | 'error'>('connected');

  useEffect(() => {
    let active = true;
    api
      .get<CrmSettingsResponse>('/crm/settings')
      .then((res) => {
        if (!active) return;
        setCrmType(res.data.provider || 'hubspot');
        setWebhookUrl(res.data.webhookUrl || '');
        setApiKeyMasked(res.data.apiKeyMasked || '');
        setGoogleCalendarEmail(res.data.googleCalendarEmail || '');
        setOutlookCalendarEmail(res.data.outlookCalendarEmail || '');
        setSipTrunkUri(res.data.sipTrunkUri || '');
        setForwardingPhoneNumber(res.data.forwardingPhoneNumber || '+18005550199');
        setCalendarSyncEnabled(res.data.calendarSyncEnabled ?? true);
        setStatus(res.data.isConnected ? 'connected' : 'disconnected');
      })
      .catch((error) => console.error('Failed to fetch CRM settings', error));
    return () => {
      active = false;
    };
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage({ type: '', text: '' });

    try {
      const res = await api.post('/crm/settings', {
        provider: crmType,
        apiKey,
        webhookUrl,
        calendarSyncEnabled,
        googleCalendarEmail,
        outlookCalendarEmail,
        sipTrunkUri,
        forwardingPhoneNumber,
      });
      setMessage({ type: 'success', text: res.data.message || 'Integration settings saved!' });
      setStatus('connected');
      setApiKeyMasked(res.data.apiKeyMasked || apiKeyMasked);
      setApiKey('');
    } catch (error: unknown) {
      const errMsg = (error as { response?: { data?: { message?: string } } })?.response?.data
        ?.message;
      setMessage({
        type: 'error',
        text: errMsg || 'Failed to save integration settings.',
      });
      setStatus('error');
    } finally {
      setLoading(false);
    }
  };

  const handleTestConnection = async () => {
    setTesting(true);
    setMessage({ type: '', text: '' });
    try {
      const res = await api.post('/crm/test');
      setMessage({ type: 'success', text: res.data.message });
      setStatus('connected');
    } catch (error: unknown) {
      const errMsg = (error as { response?: { data?: { message?: string } } })?.response?.data
        ?.message;
      setMessage({
        type: 'error',
        text: errMsg || 'Integration connection test failed.',
      });
    } finally {
      setTesting(false);
    }
  };

  const handleDownloadIcsFeed = async () => {
    try {
      const res = await api.get<string>('/crm/calendar-feed.ics', {
        responseType: 'text' as never,
      });
      const blob = new Blob([res.data], { type: 'text/calendar;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'churchill-ai-appointments.ics';
      link.click();
      URL.revokeObjectURL(url);
      setMessage({
        type: 'success',
        text: 'Downloaded churchill-ai-appointments.ics calendar file for Google Calendar / Outlook 365 import!',
      });
    } catch {
      setMessage({
        type: 'error',
        text: 'Failed to export .ics calendar feed.',
      });
    }
  };

  const activeCard = INTEGRATION_CARDS.find((c) => c.id === crmType) || INTEGRATION_CARDS[2];

  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      className="space-y-8 pb-12"
    >
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold text-slate-900 flex items-center gap-2.5">
            <Database className="w-6 h-6 text-indigo-600" />
            Connected Ecosystem &amp; Native Integrations
          </h1>
          <p className="text-slate-600 text-sm mt-1">
            Configure Google Calendar, Microsoft Outlook 365, HubSpot, Salesforce/Zoho, Zapier/Make
            Webhooks, and Twilio/SIP Trunking.
          </p>
        </div>
        <button
          type="button"
          onClick={handleDownloadIcsFeed}
          className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 text-xs font-bold text-indigo-700 transition-colors"
        >
          <Download className="w-4 h-4" />
          Export Google / Outlook (.ics) Calendar
        </button>
      </div>

      {/* 6 Native Integration Cards Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {INTEGRATION_CARDS.map((card) => {
          const isSelected = crmType === card.id;
          return (
            <button
              key={card.id}
              type="button"
              onClick={() => {
                setCrmType(card.id);
                setMessage({ type: '', text: '' });
              }}
              className={`text-left p-5 rounded-2xl border transition-all flex flex-col justify-between ${
                isSelected
                  ? 'bg-indigo-50/70 border-indigo-600 ring-2 ring-indigo-600/15 shadow-sm'
                  : 'bg-white border-slate-200 hover:border-indigo-300 shadow-2xs'
              }`}
            >
              <div>
                <div className="flex items-center justify-between mb-2">
                  <span className="font-bold text-slate-900 text-base">{card.name}</span>
                  <span className="px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
                    {card.badge}
                  </span>
                </div>
                <p className="text-xs font-semibold text-indigo-600 mb-2">{card.category}</p>
                <p className="text-xs text-slate-600 leading-relaxed">{card.desc}</p>
              </div>
              <div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between text-xs font-bold">
                <span className={isSelected ? 'text-indigo-700' : 'text-slate-500'}>
                  {isSelected ? 'Currently Editing' : 'Click to Configure'}
                </span>
                <Zap className={`w-3.5 h-3.5 ${isSelected ? 'text-indigo-600' : 'text-slate-400'}`} />
              </div>
            </button>
          );
        })}
      </div>

      {/* Active Integration Configuration Panel */}
      <div className="bg-white rounded-3xl shadow-sm border border-slate-200 p-8 relative overflow-hidden">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6 pb-6 border-b border-slate-200">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-2xl flex items-center justify-center bg-indigo-50 border border-indigo-200 text-indigo-600">
              {crmType.includes('calendar') ? (
                <Calendar className="w-6 h-6" />
              ) : crmType === 'twilio_sip' ? (
                <PhoneForwarded className="w-6 h-6" />
              ) : (
                <Link2 className="w-6 h-6" />
              )}
            </div>
            <div>
              <h3 className="text-lg font-bold text-slate-900">{activeCard.name} Configuration</h3>
              <div className="flex items-center gap-2 mt-1 text-xs font-semibold text-slate-600">
                Status:
                <span
                  className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full ${
                    status === 'connected'
                      ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                      : status === 'error'
                      ? 'bg-rose-50 text-rose-700 border border-rose-200'
                      : 'bg-slate-100 text-slate-600 border border-slate-200'
                  }`}
                >
                  {status === 'connected' && <CheckCircle2 className="w-3.5 h-3.5" />}
                  {status === 'error' && <ShieldAlert className="w-3.5 h-3.5" />}
                  {status.charAt(0).toUpperCase() + status.slice(1)}
                </span>
                {apiKeyMasked && (
                  <span className="text-xs text-slate-500 font-mono ml-1">({apiKeyMasked})</span>
                )}
              </div>
            </div>
          </div>

          <button
            type="button"
            onClick={handleTestConnection}
            disabled={testing}
            className="px-4 py-2.5 rounded-xl bg-indigo-50 border border-indigo-200 text-xs font-bold text-indigo-700 hover:bg-indigo-100 transition-colors"
          >
            {testing ? 'Verifying...' : `Verify ${activeCard.name}`}
          </button>
        </div>

        <AnimatePresence>
          {message.text && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className={`mb-6 p-4 rounded-xl ${
                message.type === 'success'
                  ? 'bg-emerald-50 border border-emerald-200 text-emerald-800'
                  : 'bg-rose-50 border border-rose-200 text-rose-800'
              } flex items-start`}
            >
              <AlertCircle className="w-5 h-5 mr-3 mt-0.5 shrink-0" />
              <p className="text-xs font-semibold leading-relaxed">{message.text}</p>
            </motion.div>
          )}
        </AnimatePresence>

        <form onSubmit={handleSubmit} className="space-y-6">
          {(crmType === 'google_calendar' || crmType === 'outlook_calendar') && (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1.5">
                  Google Calendar Account Email
                </label>
                <input
                  type="email"
                  value={googleCalendarEmail}
                  onChange={(e) => setGoogleCalendarEmail(e.target.value)}
                  placeholder="appointments@yourclinic.com"
                  className="block w-full rounded-xl border border-slate-300 bg-white py-2.5 px-3.5 text-slate-900 text-sm"
                />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1.5">
                  Microsoft Outlook 365 Calendar Email
                </label>
                <input
                  type="email"
                  value={outlookCalendarEmail}
                  onChange={(e) => setOutlookCalendarEmail(e.target.value)}
                  placeholder="reception@yourfirm.com"
                  className="block w-full rounded-xl border border-slate-300 bg-white py-2.5 px-3.5 text-slate-900 text-sm"
                />
              </div>
            </div>
          )}

          {crmType === 'twilio_sip' && (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1.5">
                  Inbound Twilio / Forwarding Target Number (E.164)
                </label>
                <input
                  type="text"
                  value={forwardingPhoneNumber}
                  onChange={(e) => setForwardingPhoneNumber(e.target.value)}
                  placeholder="+18005550199"
                  className="block w-full rounded-xl border border-slate-300 bg-white py-2.5 px-3.5 text-slate-900 text-sm"
                />
                <p className="text-[11px] text-slate-500 mt-1">
                  Dial <code>*72{forwardingPhoneNumber}</code> on your existing landline or mobile to forward calls to Churchill AI.
                </p>
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1.5">
                  BYO SIP Trunk Termination URI (Optional)
                </label>
                <input
                  type="text"
                  value={sipTrunkUri}
                  onChange={(e) => setSipTrunkUri(e.target.value)}
                  placeholder="sip:churchill-ai.pstn.twilio.com"
                  className="block w-full rounded-xl border border-slate-300 bg-white py-2.5 px-3.5 text-slate-900 text-sm"
                />
              </div>
            </div>
          )}

          <div>
            <label className="block text-xs font-bold text-slate-700 mb-1.5">
              Webhook Endpoint URL (Receives HMAC-Signed Post-Call &amp; Booking JSON Payloads)
            </label>
            <input
              type="url"
              value={webhookUrl}
              onChange={(e) => setWebhookUrl(e.target.value)}
              placeholder="https://hooks.zapier.com/hooks/catch/... or https://your-crm.com/webhooks/churchill"
              className="block w-full rounded-xl border border-slate-300 bg-white py-2.5 px-3.5 text-slate-900 text-sm"
            />
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-700 mb-1.5">
              Private API Key / Bearer Token (e.g. HubSpot <code>pat-...</code> or Salesforce/Zoho Token)
            </label>
            <input
              type="password"
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              placeholder={
                apiKeyMasked
                  ? `Stored key: ${apiKeyMasked} (enter new key to replace)`
                  : `Enter your ${activeCard.name} API key (optional if using Webhook)`
              }
              className="block w-full rounded-xl border border-slate-300 bg-white py-2.5 px-3.5 text-slate-900 text-sm"
            />
            <p className="mt-2 flex items-center gap-2 text-xs text-slate-500">
              <ShieldAlert className="w-4 h-4 text-emerald-600 shrink-0" />
              Credentials are encrypted per-tenant in MongoDB and masked in all API responses.
            </p>
          </div>

          <div className="pt-4 border-t border-slate-200 flex justify-end">
            <button
              type="submit"
              disabled={loading}
              className="inline-flex items-center px-6 py-3 text-sm font-bold rounded-xl text-white bg-indigo-600 hover:bg-indigo-500 shadow-md shadow-indigo-600/20 transition-all"
            >
              <Save className="w-4 h-4 mr-2" />
              {loading ? 'Saving...' : `Save & Activate ${activeCard.name}`}
            </button>
          </div>
        </form>
      </div>
    </motion.div>
  );
};

export default CrmSettings;
