'use client';

import React from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Plus, Pencil, Trash2 } from 'lucide-react';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import Loader from '@/components/common/loader';
import DashboardLayout from '@/app/dashboard/layout';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { currency } from '@/lib/utils';

interface CateringPlan {
  _id: string;
  name: string;
  price: number;
  kid_price?: number;
  discription?: string;
  status: string;
  plan_details: {
    category_id: {
      _id: string;
      category_name: string;
      category_image?: string;
    };
    count: number;
  }[];
}

const CateringPlansList: React.FC = () => {
  const [plans, setPlans] = React.useState<CateringPlan[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [selectedPlan, setSelectedPlan] = React.useState<CateringPlan | null>(null);
  const [openConfirm, setOpenConfirm] = React.useState(false);

  const { Toast, userInfo } = useGlobalContext();
  const router = useRouter();

  const fetchPlans = async () => {
    try {
      const restaurantId =
        userInfo?.restaurant_id?._id || sessionStorage.getItem('resId');

      if (!restaurantId) return;

      setLoading(true);
      const response = await apis.Catering.getCateringServiceList(restaurantId);

      if (response?.plans) {
        setPlans(response.plans);
      }
    } catch (error) {
      console.error(error);
      Toast.error('Failed to load catering plans');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchPlans();
  }, [userInfo]);

  // ✅ Delete handler (called after confirmation)
  const handleDelete = async () => {
    if (!selectedPlan) return;

    try {
      setLoading(true);
      await apis.Catering.deleteCateringService(selectedPlan._id);
      Toast.success('Catering plan deleted successfully!');
      setOpenConfirm(false);
      setSelectedPlan(null);
      await fetchPlans();
    } catch (error) {
      console.error('Error deleting plan:', error);
      Toast.error('Failed to delete catering plan');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader loading={loading} />
      </div>
    );
  }

  return (
    <div className="w-full max-w-6xl mx-auto p-4">
      {/* Header with Add Button */}
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-semibold">Catering Plans</h2>
        <Button
          onClick={() => router.push('/catering/add')}
          className="flex items-center font-medium gap-2 bg-[var(--primary-brand)] text-white px-4 py-2 rounded-lg text-sm hover:bg-[var(--primary-brand)] focus:bg-[var(--primary-brand)] active:bg-[var(--primary-brand)]"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Plan
        </Button>
      </div>

      {plans.length === 0 ? (
        <p className="text-gray-500 text-center py-8">No catering plans found.</p>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {plans.map((plan) => (
            <Card
              key={plan._id}
              className="border rounded-xl shadow-sm hover:shadow-md transition-shadow duration-200"
            >
              <CardContent className="p-4 space-y-3">
                <div>
                  <h3 className="font-semibold text-lg text-gray-900">
                    {plan.name}
                  </h3>
                  <span className="text-[var(--orange-500)] font-semibold text-base block mt-1">
                    {currency}{plan.price}
                  </span>
                </div>

                <div className="text-sm text-gray-700 space-y-1 pt-1">
                  {plan.plan_details.map((detail, idx) => (
                    <div key={idx} className="flex justify-between">
                      <span>{detail.category_id.category_name}</span>
                      <span className="font-medium">{detail.count}</span>
                    </div>
                  ))}
                </div>

                <div className="flex items-center justify-between border-t pt-3 mt-3">
                  <div className="flex gap-3">
                    <Button
                      variant="ghost"
                      size="sm"
                      className="text-orange-500 hover:text-orange-500 hover:bg-transparent px-2"
                      onClick={() => router.push(`/catering/edit/${plan._id}`)}
                    >
                      <Pencil className="h-4 w-4 mr-1" />
                      Edit
                    </Button>

                    <Button
                      variant="ghost"
                      size="sm"
                      className="text-red-500 hover:text-red-500 hover:bg-transparent px-2"
                      onClick={() => {
                        setSelectedPlan(plan);
                        setOpenConfirm(true);
                      }}
                    >
                      <Trash2 className="h-4 w-4 mr-1" />
                      Delete
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* ✅ Delete Confirmation Modal */}
      <AlertDialog open={openConfirm} onOpenChange={setOpenConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Catering Plan</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{' '}
              <span className="font-semibold">{selectedPlan?.name}</span>? This action
              cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>

          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setOpenConfirm(false)}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-red-500 hover:bg-red-600 text-white"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <div className="h-full overflow-y-auto p-4">
        <CateringPlansList />
      </div>
    </DashboardLayout>
  );
}
