import React, { useState, useEffect } from 'react';
import {
  Truck, Save, Key, Eye, EyeOff, CheckCircle, AlertCircle,
  RefreshCw, Globe, Phone, Mail, MapPin, Building2, Copy,
  Check, X, Info, Settings, Shield, Clock, Download, Upload,
  XCircle
} from 'lucide-react';

interface CourierSettings {
  api_key: string;
  secret_key: string;
  webhook_token: string;
  business_name: string;
  business_phone: string;
  business_address: string;
  business_email: string;
  status: number;
  has_api_keys?: boolean;
}

interface TestResult {
  success: boolean;
  message: string;
  balance?: number;
}

interface WebhookInfo {
  webhook_url: string;
  webhook_token: string;
  webhook_secret?: string;
}

const API_BASE = '/api';
const getTenantToken = () => localStorage.getItem('tenant_token') || '';
const authHeaders = (extra: Record<string, string> = {}) => ({
  'Content-Type': 'application/json',
  'X-Tenant-Token': getTenantToken(),
  ...extra,
});

interface SiteSettings {
  logo?: string;
  siteName?: string;
  [key: string]: any;
}

interface CourierSettingsProps {
  settings?: SiteSettings;
}

const CourierSettings: React.FC<CourierSettingsProps> = ({ settings: siteSettings }) => {
  // State
  const [settings, setSettings] = useState<CourierSettings>({
    api_key: '',
    secret_key: '',
    webhook_token: '',
    business_name: 'shophyfast Masala',
    business_phone: '+880 1790-014219',
    business_address: 'Hathazari, Chattogram, Bangladesh',
    business_email: 'hello@shophyfast.com',
    status: 1,
    has_api_keys: false
  });

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<TestResult | null>(null);
  const [webhookInfo, setWebhookInfo] = useState<WebhookInfo | null>(null);
  const [showApiKey, setShowApiKey] = useState(false);
  const [showSecretKey, setShowSecretKey] = useState(false);
  const [copied, setCopied] = useState<string | null>(null);
  const [stats, setStats] = useState<any>(null);
  const [activeTab, setActiveTab] = useState<'settings' | 'webhook' | 'stats'>('settings');

  // Notification state
  const [notification, setNotification] = useState<{
    message: string;
    type: 'success' | 'error';
    visible: boolean;
  }>({
    message: '',
    type: 'success',
    visible: false
  });

  // Load settings on mount
  useEffect(() => {
    fetchSettings();
    fetchWebhookInfo();
    fetchStats();
  }, []);

  // Show toast notification
  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setNotification({ message, type, visible: true });
    setTimeout(() => setNotification(prev => ({ ...prev, visible: false })), 3000);
  };

  // Copy to clipboard
  const copyToClipboard = (text: string, field: string) => {
    navigator.clipboard.writeText(text);
    setCopied(field);
    setTimeout(() => setCopied(null), 2000);
    showToast('Copied to clipboard!', 'success');
  };

  // Fetch settings
  const fetchSettings = async () => {
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE}/admin/courier-settings`, {
        headers: authHeaders(),
      });
      const data = await response.json();

      if (data.success && data.data) {
        setSettings(prev => ({
          ...prev,
          ...data.data,
          api_key: '',
          secret_key: ''
        }));
      }
    } catch (error) {
      console.error('Error fetching settings:', error);
      showToast('Failed to load settings', 'error');
    } finally {
      setLoading(false);
    }
  };

  // Fetch webhook info
  const fetchWebhookInfo = async () => {
    try {
      const response = await fetch(`${API_BASE}/admin/courier-settings?action=webhook`, {
        headers: authHeaders(),
      });
      const data = await response.json();

      if (data.success) {
        setWebhookInfo(data.data);
      }
    } catch (error) {
      console.error('Error fetching webhook info:', error);
    }
  };

  // Fetch statistics
  const fetchStats = async () => {
    try {
      const response = await fetch(`${API_BASE}/admin/courier-settings?action=stats`, {
        headers: authHeaders(),
      });
      const data = await response.json();

      if (data.success) {
        setStats(data.data);
      }
    } catch (error) {
      console.error('Error fetching stats:', error);
    }
  };

  // Test API connection
  const testConnection = async () => {
    if (!settings.has_api_keys && (!settings.api_key || !settings.secret_key)) {
      showToast('Please enter API Key and Secret Key first', 'error');
      return;
    }

    setTesting(true);
    setTestResult(null);

    try {
      const response = await fetch(`${API_BASE}/admin/courier-settings?action=test`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({
          api_key: settings.api_key,
          secret_key: settings.secret_key
        })
      });

      const data = await response.json();

      if (data.success) {
        setTestResult({
          success: true,
          message: data.message,
          balance: data.balance
        });
        showToast('API connection successful!', 'success');
      } else {
        setTestResult({
          success: false,
          message: data.error || 'Connection failed'
        });
        showToast('API connection failed', 'error');
      }
    } catch (error) {
      console.error('Error testing connection:', error);
      setTestResult({
        success: false,
        message: 'Network error. Please try again.'
      });
      showToast('Network error', 'error');
    } finally {
      setTesting(false);
    }
  };

  // Save settings
  const saveSettings = async () => {
    if (!settings.has_api_keys && (!settings.api_key || !settings.secret_key)) {
      showToast('API Key and Secret Key are required', 'error');
      return;
    }

    setSaving(true);

    try {
      const response = await fetch(`${API_BASE}/admin/courier-settings`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(settings)
      });

      const data = await response.json();

      if (data.success) {
        showToast(data.message || 'Settings saved successfully!', 'success');
        setSettings(prev => ({
          ...prev,
          ...data.data,
          api_key: '',
          secret_key: ''
        }));
        fetchSettings();
        fetchWebhookInfo();
      } else {
        if (data.errors) {
          data.errors.forEach((err: string) => showToast(err, 'error'));
        } else {
          showToast(data.error || 'Failed to save settings', 'error');
        }
      }
    } catch (error) {
      console.error('Error saving settings:', error);
      showToast('Network error. Please try again.', 'error');
    } finally {
      setSaving(false);
    }
  };

  // Reset settings
  const resetSettings = async () => {
    if (!confirm('Are you sure you want to reset all courier settings? This action cannot be undone.')) {
      return;
    }

    setSaving(true);
    try {
      const response = await fetch(`${API_BASE}/admin/courier-settings?action=reset`, {
        method: 'POST',
        headers: authHeaders(),
      });

      const data = await response.json();

      if (data.success) {
        showToast('Settings reset successfully', 'success');
        fetchSettings();
        fetchStats();
      } else {
        showToast(data.error || 'Failed to reset settings', 'error');
      }
    } catch (error) {
      console.error('Error resetting settings:', error);
      showToast('Network error', 'error');
    } finally {
      setSaving(false);
    }
  };

  // Handle input change
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setSettings(prev => ({ ...prev, [name]: value }));
  };

  // Tab button classes
  const getTabButtonClass = (tabName: string) => {
    return `flex-1 py-4 rounded-2xl font-black transition-all ${activeTab === tabName
      ? 'bg-purple-600 text-white shadow-lg'
      : 'text-slate-400 hover:text-purple-600'
      }`;
  };

  // Test result classes
  const getTestResultClass = () => {
    return testResult?.success
      ? 'bg-green-50 border border-green-200'
      : 'bg-red-50 border border-red-200';
  };

  return (
    <div className="space-y-6 animate-fade-in-up">
      {/* Notification Toast */}
      {notification.visible && (
        <div className={`fixed top-6 right-6 z-[9999] px-6 py-4 rounded-2xl shadow-2xl animate-slide-in-right flex items-center gap-3 ${notification.type === 'success' ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
          }`}>
          {notification.type === 'success' ? <CheckCircle size={20} /> : <AlertCircle size={20} />}
          <span className="font-bold">{notification.message}</span>
        </div>
      )}

      {/* Header */}
      <div className="bg-gradient-to-r from-purple-600 to-purple-800 text-white p-8 rounded-[40px] shadow-xl">
        <div className="flex items-center gap-5">
          {/* ✅ Shop Logo (from admin branding settings) */}
          <div className="w-20 h-20 bg-white rounded-3xl flex items-center justify-center shadow-lg overflow-hidden shrink-0">
            {siteSettings?.logo ? (
              <img
                src={siteSettings.logo}
                alt="Shop Logo"
                className="w-full h-full object-contain p-1"
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = 'none';
                  (e.target as HTMLImageElement).nextElementSibling?.removeAttribute('style');
                }}
              />
            ) : null}
            <Truck
              size={40}
              className="text-purple-600"
              style={{ display: siteSettings?.logo ? 'none' : 'block' }}
            />
          </div>
          <div>
            <h1 className="text-4xl md:text-5xl font-black">SteadFast Courier</h1>
            <p className="text-white/80 text-lg mt-2">
              Configure your SteadFast API settings and manage courier integration
            </p>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="bg-white dark:bg-slate-900 rounded-[32px] border shadow-sm p-2 flex gap-2">
        <button
          onClick={() => setActiveTab('settings')}
          className={getTabButtonClass('settings')}
        >
          <Settings size={20} className="inline mr-2" />
          Settings
        </button>
        <button
          onClick={() => setActiveTab('webhook')}
          className={getTabButtonClass('webhook')}
        >
          <Globe size={20} className="inline mr-2" />
          Webhook
        </button>
        <button
          onClick={() => setActiveTab('stats')}
          className={getTabButtonClass('stats')}
        >
          <Clock size={20} className="inline mr-2" />
          Statistics
        </button>
      </div>

      {/* Tab Content */}
      {activeTab === 'settings' && (
        <>
          {/* API Settings Card */}
          <div className="bg-white dark:bg-slate-900 rounded-[40px] border shadow-sm overflow-hidden">
            <div className="p-8 border-b bg-gradient-to-r from-slate-50 to-gray-100">
              <h2 className="text-2xl font-black flex items-center gap-2 text-black">
                <Key className="text-black" size={24} />
                API Configuration
              </h2>
              <p className="text-slate-500 mt-1">
                {settings.has_api_keys
                  ? 'API keys are already configured. Enter new keys to update.'
                  : 'Enter your SteadFast API credentials to get started'}
              </p>
            </div>

            <div className="p-8 space-y-6">
              {/* API Key */}
              <div>
                <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                  API Key {!settings.has_api_keys && '*'}
                </label>
                <div className="relative">
                  <Key className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
                  <input
                    type={showApiKey ? 'text' : 'password'}
                    name="api_key"
                    value={settings.api_key}
                    onChange={handleChange}
                    className="w-full pl-12 pr-12 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                    placeholder={settings.has_api_keys ? 'Enter new API key to update' : 'Enter your SteadFast API Key'}
                  />
                  <button
                    onClick={() => setShowApiKey(!showApiKey)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-purple-600"
                    type="button"
                  >
                    {showApiKey ? <EyeOff size={20} /> : <Eye size={20} />}
                  </button>
                </div>
              </div>

              {/* Secret Key */}
              <div>
                <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                  Secret Key {!settings.has_api_keys && '*'}
                </label>
                <div className="relative">
                  <Key className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
                  <input
                    type={showSecretKey ? 'text' : 'password'}
                    name="secret_key"
                    value={settings.secret_key}
                    onChange={handleChange}
                    className="w-full pl-12 pr-12 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                    placeholder={settings.has_api_keys ? 'Enter new secret key to update' : 'Enter your SteadFast Secret Key'}
                  />
                  <button
                    onClick={() => setShowSecretKey(!showSecretKey)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-purple-600"
                    type="button"
                  >
                    {showSecretKey ? <EyeOff size={20} /> : <Eye size={20} />}
                  </button>
                </div>
              </div>

              {/* Test Connection Button */}
              <div className="pt-4">
                <button
                  onClick={testConnection}
                  disabled={testing || !settings.api_key || !settings.secret_key}
                  className="px-6 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-purple-300 text-white rounded-2xl font-black flex items-center gap-2 transition-all"
                >
                  <RefreshCw size={18} className={testing ? 'animate-spin' : ''} />
                  {testing ? 'Testing...' : 'Test Connection'}
                </button>

                {/* Test Result */}
                {testResult && (
                  <div className={`mt-4 p-4 rounded-2xl ${getTestResultClass()}`}>
                    <div className="flex items-center gap-2">
                      {testResult.success ? (
                        <CheckCircle size={18} className="text-green-600" />
                      ) : (
                        <XCircle size={18} className="text-red-600" />
                      )}
                      <span className={testResult.success ? 'text-green-700' : 'text-red-700'}>
                        {testResult.message}
                      </span>
                    </div>
                    {testResult.balance !== undefined && (
                      <p className="mt-2 text-sm text-green-700 font-bold">
                        Current Balance: ৳{testResult.balance}
                      </p>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Business Info Card */}
          <div className="bg-white dark:bg-slate-900 rounded-[40px] border shadow-sm overflow-hidden">
            <div className="p-8 border-b bg-gradient-to-r from-slate-50 to-gray-100">
              <h2 className="text-2xl font-black flex items-center gap-2 text-black">
                <Building2 className="text-black" size={24} />
                Business Information
              </h2>
              <p className="text-slate-500 mt-1">This information will appear on courier labels</p>
            </div>

            <div className="p-8 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Business Name */}
                <div>
                  <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                    Business Name
                  </label>
                  <input
                    type="text"
                    name="business_name"
                    value={settings.business_name}
                    onChange={handleChange}
                    className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                    placeholder="Enter business name"
                  />
                </div>

                {/* Business Phone */}
                <div>
                  <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                    <Phone size={14} className="inline mr-1" />
                    Phone
                  </label>
                  <input
                    type="text"
                    name="business_phone"
                    value={settings.business_phone}
                    onChange={handleChange}
                    className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                    placeholder="Enter phone number"
                  />
                </div>

                {/* Business Email */}
                <div>
                  <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                    <Mail size={14} className="inline mr-1" />
                    Email
                  </label>
                  <input
                    type="email"
                    name="business_email"
                    value={settings.business_email}
                    onChange={handleChange}
                    className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                    placeholder="Enter email address"
                  />
                </div>

                {/* Business Address - Full width */}
                <div className="md:col-span-2">
                  <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                    <MapPin size={14} className="inline mr-1" />
                    Address
                  </label>
                  <textarea
                    name="business_address"
                    value={settings.business_address}
                    onChange={handleChange}
                    rows={3}
                    className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                    placeholder="Enter business address"
                  />
                </div>
              </div>
            </div>
          </div>
        </>
      )}

      {/* Webhook Tab */}
      {activeTab === 'webhook' && webhookInfo && (
        <div className="bg-white dark:bg-slate-900 rounded-[40px] border shadow-sm overflow-hidden">
          <div className="p-8 border-b bg-gradient-to-r from-slate-50 to-gray-100">
            <h2 className="text-2xl font-black flex items-center gap-2 text-black">
              <Globe className="text-black" size={24} />
              Webhook Configuration
            </h2>
            <p className="text-slate-500 mt-1">
              Use this URL in your SteadFast dashboard for automatic status updates
            </p>
          </div>

          <div className="p-8 space-y-8">
            {/* Webhook URL */}
            <div>
              <label className="text-xs font-black uppercase text-purple-600 ml-2 mb-2 block">
                Webhook URL
              </label>
              <div className="flex gap-2">
                <div className="flex-1 bg-purple-50 p-4 rounded-2xl font-mono font-bold text-purple-700 text-sm break-all border-2 border-purple-100">
                  {webhookInfo.webhook_url}
                </div>
                <button
                  onClick={() => copyToClipboard(webhookInfo.webhook_url, 'url')}
                  className="px-6 py-4 bg-purple-100 text-purple-700 font-bold rounded-2xl hover:bg-purple-200 transition-all flex items-center gap-2"
                >
                  {copied === 'url' ? <Check size={18} className="text-purple-600" /> : <Copy size={18} />}
                  Copy
                </button>
              </div>
            </div>

            {/* Webhook Token */}
            <div>
              <label className="text-xs font-black uppercase text-purple-600 ml-2 mb-2 block">
                Webhook Token (for verification)
              </label>
              <div className="flex gap-2">
                <div className="flex-1 bg-purple-50 p-4 rounded-2xl font-mono font-bold text-purple-700 text-sm break-all border-2 border-purple-100">
                  {webhookInfo.webhook_token}
                </div>
                <button
                  onClick={() => copyToClipboard(webhookInfo.webhook_token, 'token')}
                  className="px-6 py-4 bg-purple-100 text-purple-700 font-bold rounded-2xl hover:bg-purple-200 transition-all flex items-center gap-2"
                >
                  {copied === 'token' ? <Check size={18} className="text-purple-600" /> : <Copy size={18} />}
                  Copy
                </button>
              </div>
            </div>

            {/* Instructions */}
            <div className="bg-purple-50 p-6 rounded-3xl">
              <h3 className="font-black text-purple-800 mb-3 flex items-center gap-2">
                <Info size={18} />
                How to set up webhook
              </h3>
              <ol className="list-decimal list-inside space-y-2 text-sm text-purple-700">
                <li>Go to your SteadFast Merchant Dashboard</li>
                <li>Navigate to API Settings / Webhook Configuration</li>
                <li>Paste the Webhook URL above</li>
                <li>Set the Webhook Token as verification header (if required)</li>
                <li>Save settings in SteadFast dashboard</li>
                <li>Test by updating an order status</li>
              </ol>
            </div>
          </div>
        </div>
      )}

      {/* Statistics Tab */}
      {activeTab === 'stats' && (
        <div className="bg-white dark:bg-slate-900 rounded-[40px] border shadow-sm overflow-hidden">
          <div className="p-8 border-b bg-gradient-to-r from-slate-50 to-gray-100">
            <h2 className="text-2xl font-black flex items-center gap-2 text-black">
              <Clock className="text-black" size={24} />
              Courier Statistics
            </h2>
            <p className="text-slate-500 mt-1">
              Overview of your courier operations
            </p>
          </div>

          <div className="p-8">
            {stats ? (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                {/* Total Orders */}
                <div className="p-6 bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-3xl shadow-lg">
                  <p className="text-4xl font-black">{stats.total_orders || 0}</p>
                  <p className="text-sm mt-2 opacity-90">Total Orders</p>
                </div>

                {/* Delivered */}
                <div className="p-6 bg-gradient-to-br from-green-500 to-green-600 text-white rounded-3xl shadow-lg">
                  <p className="text-4xl font-black">{stats.delivered || 0}</p>
                  <p className="text-sm mt-2 opacity-90">Delivered</p>
                </div>

                {/* Pending */}
                <div className="p-6 bg-gradient-to-br from-amber-500 to-amber-600 text-white rounded-3xl shadow-lg">
                  <p className="text-4xl font-black">{stats.pending || 0}</p>
                  <p className="text-sm mt-2 opacity-90">Pending</p>
                </div>

                {/* Success Rate */}
                <div className="p-6 bg-gradient-to-br from-purple-500 to-purple-600 text-white rounded-3xl shadow-lg">
                  <p className="text-4xl font-black">{stats.success_rate || 0}%</p>
                  <p className="text-sm mt-2 opacity-90">Success Rate</p>
                </div>

                {/* Today */}
                <div className="p-6 bg-slate-100 dark:bg-slate-800 rounded-2xl">
                  <p className="text-2xl font-black">{stats.today || 0}</p>
                  <p className="text-xs text-slate-400">Today</p>
                </div>

                {/* This Week */}
                <div className="p-6 bg-slate-100 dark:bg-slate-800 rounded-2xl">
                  <p className="text-2xl font-black">{stats.this_week || 0}</p>
                  <p className="text-xs text-slate-400">This Week</p>
                </div>

                {/* This Month */}
                <div className="p-6 bg-slate-100 dark:bg-slate-800 rounded-2xl">
                  <p className="text-2xl font-black">{stats.this_month || 0}</p>
                  <p className="text-xs text-slate-400">This Month</p>
                </div>

                {/* With Labels */}
                <div className="p-6 bg-slate-100 dark:bg-slate-800 rounded-2xl">
                  <p className="text-2xl font-black">{stats.with_labels || 0}</p>
                  <p className="text-xs text-slate-400">Labels Generated</p>
                </div>
              </div>
            ) : (
              <div className="text-center py-12 text-slate-400">
                <Clock size={48} className="mx-auto mb-4 opacity-30" />
                <p>Loading statistics...</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Save Button - Sticky Footer */}
      <div className="sticky bottom-6 bg-white dark:bg-slate-900 p-6 rounded-[32px] border shadow-2xl">
        <div className="flex gap-4">
          <button
            onClick={saveSettings}
            disabled={saving}
            className="flex-1 py-5 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white rounded-2xl font-black text-lg flex items-center justify-center gap-3 shadow-xl transition-all active:scale-95"
          >
            <Save size={20} />
            {saving ? 'Saving...' : 'Save Settings'}
          </button>

          <button
            onClick={resetSettings}
            disabled={saving}
            className="px-8 py-5 bg-red-600 hover:bg-red-700 text-white rounded-2xl font-black flex items-center gap-2 transition-all"
          >
            <X size={18} />
            Reset
          </button>
        </div>
      </div>
    </div>
  );
};

export default CourierSettings;