import { useState } from 'react';
import Button from '../../components/Buttons';
import Toast from '../../components/Toast';
import { settingsApi } from '../../api/settingsApi';

const WooSync = () => {
  const [syncingProducts, setSyncingProducts] = useState(false);
  const [syncingOrders, setSyncingOrders] = useState(false);
  
  const [productLog, setProductLog] = useState<string>('');
  const [orderLog, setOrderLog] = useState<string>('');

  const [toast, setToast] = useState<{
    show: boolean;
    message: string;
    type: 'success' | 'error' | 'info';
  }>({
    show: false,
    message: '',
    type: 'success',
  });

  const handleSyncProducts = async () => {
    setSyncingProducts(true);
    setProductLog('Initiating WooCommerce products sync... Please wait.\nThis request might take a few moments to communicate with WooCommerce APIs...\n');
    try {
      const res = await settingsApi.syncWooProducts();
      if (res.success) {
        setProductLog((prev) => prev + '\n[SUCCESS] Sync Completed!\n\nDetailed Output:\n' + res.output);
        setToast({
          show: true,
          message: res.message || 'Products synced successfully!',
          type: 'success',
        });
      } else {
        setProductLog((prev) => prev + '\n[ERROR] Sync Failed!\n\nReason:\n' + res.output);
        setToast({
          show: true,
          message: res.message || 'Failed to sync products.',
          type: 'error',
        });
      }
    } catch (err: any) {
      console.error(err);
      const errMsg = err.response?.data?.message || err.message || 'Server error occurred during sync.';
      const errOutput = err.response?.data?.output || '';
      setProductLog((prev) => prev + `\n[ERROR] Request failed!\n\nMessage: ${errMsg}\n${errOutput ? `Details: ${errOutput}` : ''}`);
      setToast({
        show: true,
        message: errMsg,
        type: 'error',
      });
    } finally {
      setSyncingProducts(false);
    }
  };

  const handleSyncOrders = async () => {
    setSyncingOrders(true);
    setOrderLog('Initiating WooCommerce orders sync... Please wait.\nThis request might take a few moments to communicate with WooCommerce APIs...\n');
    try {
      const res = await settingsApi.syncWooOrders();
      if (res.success) {
        setOrderLog((prev) => prev + '\n[SUCCESS] Sync Completed!\n\nDetailed Output:\n' + res.output);
        setToast({
          show: true,
          message: res.message || 'Orders synced successfully!',
          type: 'success',
        });
      } else {
        setOrderLog((prev) => prev + '\n[ERROR] Sync Failed!\n\nReason:\n' + res.output);
        setToast({
          show: true,
          message: res.message || 'Failed to sync orders.',
          type: 'error',
        });
      }
    } catch (err: any) {
      console.error(err);
      const errMsg = err.response?.data?.message || err.message || 'Server error occurred during sync.';
      const errOutput = err.response?.data?.output || '';
      setOrderLog((prev) => prev + `\n[ERROR] Request failed!\n\nMessage: ${errMsg}\n${errOutput ? `Details: ${errOutput}` : ''}`);
      setToast({
        show: true,
        message: errMsg,
        type: 'error',
      });
    } finally {
      setSyncingOrders(false);
    }
  };

  return (
    <div className="space-y-6 max-w-5xl mx-auto">
      {/* Toast Notification */}
      <Toast
        show={toast.show}
        message={toast.message}
        type={toast.type}
        onClose={() => setToast({ ...toast, show: false })}
      />

      <div className="bg-white rounded-lg border border-slate-100 p-6 shadow-sm">
        <h1 className="text-xl font-bold text-[#3B2F28] mb-2">WooCommerce Data Synchronization</h1>
        <p className="text-sm text-slate-500">
          Manually pull active products, variations, inventory stock, and historical order details directly from your WooCommerce store into the local CRM database.
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Product Sync Section */}
        <div className="bg-white rounded-lg border border-slate-100 p-5 flex flex-col justify-between shadow-sm">
          <div>
            <div className="flex items-center space-x-3 mb-4">
              <div className="p-3 bg-amber-50 rounded-lg text-amber-600">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                </svg>
              </div>
              <div>
                <h2 className="text-md font-semibold text-[#3B2F28]">Sync Products & Inventory</h2>
                <p className="text-xs text-slate-400">Products, Variations, Images & Categories</p>
              </div>
            </div>
            <p className="text-sm text-slate-600 mb-4 leading-relaxed">
              Fetches all product items and variable variations. Matches SKU mappings, category labels, image links, and sets the current web quantity (<code className="text-xs bg-slate-100 px-1 py-0.5 rounded text-amber-700">web_qty</code>) values.
            </p>
          </div>
          <div>
            <div className="mb-4">
              <label className="text-xs font-semibold text-slate-500 mb-1 block">Product Sync Output Log</label>
              <div className="w-full bg-[#1A1A1A] border border-[#2D2D2D] rounded-lg p-3 text-xs font-mono text-[#D4D4D4] h-40 overflow-y-auto whitespace-pre-wrap">
                {productLog || 'Ready. Click sync to retrieve logs...'}
              </div>
            </div>
            <div className="flex justify-end">
              <Button
                onClick={handleSyncProducts}
                disabled={syncingProducts || syncingOrders}
                className="w-full md:w-auto"
              >
                {syncingProducts ? (
                  <div className="flex items-center justify-center space-x-2">
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
                    <span>Syncing Products...</span>
                  </div>
                ) : (
                  'Sync Products Now'
                )}
              </Button>
            </div>
          </div>
        </div>

        {/* Order Sync Section */}
        <div className="bg-white rounded-lg border border-slate-100 p-5 flex flex-col justify-between shadow-sm">
          <div>
            <div className="flex items-center space-x-3 mb-4">
              <div className="p-3 bg-amber-50 rounded-lg text-amber-600">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                </svg>
              </div>
              <div>
                <h2 className="text-md font-semibold text-[#3B2F28]">Sync Orders History</h2>
                <p className="text-xs text-slate-400">Order Totals, Items, Phone & Statuses</p>
              </div>
            </div>
            <p className="text-sm text-slate-600 mb-4 leading-relaxed">
              Fetches recent WooCommerce sales orders, matches web buyers, creates customers in CRM if missing, registers items, and synchronizes overall payment and order processing statuses.
            </p>
          </div>
          <div>
            <div className="mb-4">
              <label className="text-xs font-semibold text-slate-500 mb-1 block">Order Sync Output Log</label>
              <div className="w-full bg-[#1A1A1A] border border-[#2D2D2D] rounded-lg p-3 text-xs font-mono text-[#D4D4D4] h-40 overflow-y-auto whitespace-pre-wrap">
                {orderLog || 'Ready. Click sync to retrieve logs...'}
              </div>
            </div>
            <div className="flex justify-end">
              <Button
                onClick={handleSyncOrders}
                disabled={syncingProducts || syncingOrders}
                className="w-full md:w-auto"
              >
                {syncingOrders ? (
                  <div className="flex items-center justify-center space-x-2">
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
                    <span>Syncing Orders...</span>
                  </div>
                ) : (
                  'Sync Orders Now'
                )}
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default WooSync;
