'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import {
  Plus,
  CookingPot,
  Clock,
  Store,
  FileText,
  AlertTriangle,
} from 'lucide-react';
import { Dialog, DialogContent } from '@/components/ui/dialog';

const QuickActionsSection = () => {
  const router = useRouter();
  const { setActiveModal, Toast, userInfo, setUserInfo, getProfile } = useGlobalContext();
  const [downloading, setDownloading] = useState(false);
  const [togglingStore, setTogglingStore] = useState(false);
  const [showVerificationModal, setShowVerificationModal] = useState(false);

  const handleDownloadSalesReport = async () => {
    setDownloading(true);
    try {
      const res: any = await apis.Report.downloadSalesReport();
      const downloadUrl =
        res?.download_url ||
        res?.data?.download_url ||
        res?.data?.url ||
        res?.data?.file_url ||
        res?.url ||
        (typeof res?.data === 'string' ? res.data : null);

      if (downloadUrl && typeof downloadUrl === 'string' && downloadUrl.startsWith('http')) {
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.target = '_blank';
        link.setAttribute('download', 'sales-report.pdf');
        link.setAttribute('rel', 'noopener noreferrer');
        document.body.appendChild(link);
        link.click();
        link.remove();
        if (Toast?.success) Toast.success(res?.message || 'Sales report downloaded successfully');
      } else if (res?.message) {
        if (Toast?.success) Toast.success(res.message);
      } else {
        if (Toast?.error) Toast.error('Failed to get sales report download URL');
      }
    } catch (error: any) {
      console.error('Error downloading sales report:', error);
      if (Toast?.error) Toast.error(error);
    } finally {
      setDownloading(false);
    }
  };

  const handleToggleStore = async () => {
    if (userInfo?.restaurant_id?.is_restaurant_verified === false) {
      setShowVerificationModal(true);
      return;
    }

    const isCurrentlyOnline = userInfo?.restaurant_id?.status === 'online';
    const nextStatus = !isCurrentlyOnline;

    setTogglingStore(true);
    try {
      const params = new URLSearchParams({
        status: nextStatus ? 'online' : 'offline',
        restaurant_id: userInfo?.restaurant_id?._id || ''
      });

      const res: any = await apis.Auth.resUpdate(params.toString());
      if (setUserInfo) {
        setUserInfo((prev: any) => {
          if (!prev) return prev;
          return {
            ...prev,
            restaurant_id: {
              ...prev.restaurant_id,
              status: nextStatus ? 'online' : 'offline'
            }
          };
        });
      }

      if (getProfile) {
        getProfile();
      }

      if (typeof window !== 'undefined') {
        window.dispatchEvent(
          new CustomEvent('vendorStatusChanged', {
            detail: { status: nextStatus ? 'online' : 'offline' }
          })
        );
      }

      const msg = res?.message || `Store is now ${nextStatus ? 'open' : 'closed'}`;
      if (Toast?.success) Toast.success(msg);
    } catch (error: any) {
      console.error('Error toggling store status:', error);
      if (Toast?.error) Toast.error(error);
    } finally {
      setTogglingStore(false);
    }
  };

  const isStoreOpen = userInfo?.restaurant_id?.status === 'online';

  const isFood =
    userInfo?.restaurant_id?.type ||
    userInfo?.restaurant_id?.restaurant_type ||
    userInfo?.type ||
    userInfo?.restaurant_type
      ? userInfo?.restaurant_id?.type === 'food' ||
        userInfo?.restaurant_id?.restaurant_type === 'food' ||
        userInfo?.type === 'food' ||
        userInfo?.restaurant_type === 'food'
      : true;

  const actions = [
    {
      title: 'Add Product',
      icon: <Plus size={20} className="stroke-[2.5]" />,
      onClick: () => {
        if (isFood) {
          router.push('/menu');
        } else {
          router.push('/grocery');
        }
      },
    },
    {
      title: 'View Orders',
      icon: <CookingPot size={20} className="stroke-[2]" />,
      onClick: () => router.push('/orders/ongoing?status=ongoing&page=1&limit=15'),
    },
    {
      title: 'Update Store Timings',
      icon: <Clock size={20} className="stroke-[2]" />,
      onClick: () => {
        if (setActiveModal) setActiveModal('timings');
      },
    },
    {
      title: isStoreOpen ? 'Close Store' : 'Open Store',
      icon: togglingStore ? (
        <div className="w-5 h-5 border-2 border-[var(--primary-brand)] border-t-transparent rounded-full animate-spin" />
      ) : (
        <Store size={20} className="stroke-[2]" />
      ),
      onClick: handleToggleStore,
    },
    {
      title: 'Download Sales Report',
      icon: downloading ? (
        <div className="w-5 h-5 border-2 border-[var(--primary-brand)] border-t-transparent rounded-full animate-spin" />
      ) : (
        <FileText size={20} className="stroke-[2]" />
      ),
      onClick: handleDownloadSalesReport,
    },
  ];

  return (
    <>
      <div className="w-full bg-white rounded-2xl p-6 border border-[#F0F0F2] shadow-sm flex flex-col justify-between min-h-[300px]">
        <div>
          <h3 className="text-base font-bold text-gray-900 mb-5">Quick Actions</h3>

          <div className="grid grid-cols-3 gap-3.5">
            {actions.map((action, idx) => (
              <div
                key={idx}
                onClick={action.onClick}
                className="bg-white border border-gray-100/90 rounded-2xl p-4 flex flex-col items-center justify-center text-center cursor-pointer hover:border-gray-200 hover:shadow-xs transition-all group min-h-[110px]"
              >
                <div className="w-10 h-10 rounded-xl bg-orange-50 flex items-center justify-center text-[var(--primary-brand)] transition-transform group-hover:scale-105 shrink-0">
                  {action.icon}
                </div>
                <span className="text-xs font-bold text-gray-800 mt-2.5 leading-snug">
                  {action.title}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {showVerificationModal && (
        <Dialog open={showVerificationModal} onOpenChange={setShowVerificationModal}>
          <DialogContent className="max-w-[400px] p-0 border-0 bg-white rounded-[24px] shadow-2xl overflow-hidden focus:outline-none">
            <div className="relative pt-10 pb-8 px-6 flex flex-col items-center text-center">
              <div className="relative mb-6">
                <div className="absolute inset-0 bg-[var(--orange-100)] rounded-full animate-ping opacity-20" style={{ animationDuration: '3s' }}></div>
                <div className="absolute inset-[-4px] bg-[var(--orange-50)] rounded-full opacity-50"></div>
                <div className="relative flex items-center justify-center w-20 h-20 bg-white rounded-full shadow-xl shadow-[var(--orange-100)]/50">
                  <AlertTriangle className="w-10 h-10 text-[var(--primary-brand)]" strokeWidth={1.5} />
                </div>
              </div>

              <div className="space-y-3">
                <h2 className="text-[24px] font-bold text-gray-900 leading-tight">
                  Verification Pending
                </h2>
                <p className="text-[15px] font-medium text-gray-400/80 leading-relaxed px-4">
                  Your store is not verified by admin yet. It will remain closed until approval is completed.
                </p>
              </div>

              <div className="flex flex-col w-full gap-3 mt-10">
                <button
                  className="w-full py-4 text-[16px] font-bold text-white bg-[var(--primary-brand)] rounded-2xl shadow-lg shadow-[var(--orange-100)] hover:opacity-90 active:scale-[0.98] transition-all duration-200"
                  onClick={() => setShowVerificationModal(false)}
                >
                  Okay
                </button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      )}
    </>
  );
};

export default QuickActionsSection;
