"use client";
import React, { useEffect, useRef, useState } from "react";
import { Clock9, EllipsisVertical, Heart, Package, Plus, Calendar } from "lucide-react";
import { Icons } from "../icons";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { Modal } from "@/components/ui/modal";
import { Input } from "../ui/input";
import { CardContent } from "../ui/card";
import { useGlobalContext } from "@/context/Provider";
import { Textarea } from "../ui/textarea";
import { calculateActiveDuration, formatOrderCount, getTodayTimings } from "@/lib/utils";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";


const RestroBanner = ({ data, distance }: any) => {
  const { Toast, userInfo } = useGlobalContext();
  const address = (data?.address?.area || data?.address?.name || data?.address?.city || "")?.split(",");
  const [showReport, setShowReport] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [blobFile, setBlobFile] = useState<File | null>(null);
  const [fileName, setFileName] = useState("");
  const [image, setImage] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [desc, setDesc] = useState("");
  const [isFav, setIsFav] = useState(data?.is_fav);
  const [reportReasons, setReportReasons] = useState([]);
  const [selectedReason, setSelectedReason] = useState<string | undefined>(undefined);

  useEffect(() => {
    setIsFav(data?.is_fav);
  }, [data?.is_fav]);

  const handleFileSelect = () => {
    if (fileInputRef?.current) {
      fileInputRef.current.click();
    }
  };

  const handleUploadImage = async (file: File) => {
    try {
      setLoading(true);
      setProgress(0);

      const apiRes = await apis.Common.uploadFile("file", file);
      setImage(apiRes?.key);
      Toast.success("Image uploaded successfully!");
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    const file = event.target.files?.[0];

    if (file) {
      const maxFileSize = 5 * 1024 * 1024; // 5MB Limit
      const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];

      if (!allowedTypes.includes(file.type)) {
        Toast.error("Only JPG and PNG images are allowed.");
        return;
      }

      if (file.size > maxFileSize) {
        Toast.error("Image size cannot be more than 5MB.");
        return;
      }

      setBlobFile(file);
      handleUploadImage(file);
    }
  };

  useEffect(() => {
    if (isOpen) {
      getReasons();
    }
  }, [isOpen]);

  const getReasons = async () => {
    try {
      const res = await apis.Auth.getReport("type=customer_restaurant");
      setReportReasons(res?.data || []);
    } catch (err) {
      Toast.error(err);
    }
  };


  const handleClear = () => {
    setBlobFile(null);
    setProgress(0);
    setFileName("");
    setImage("");
  };
  const handleReport = async () => {
    let payload = {
      restaurant_id: data?._id,
      description: desc,
      image: image,
      report_reason_id: selectedReason,
    };
    try {
      const apiRes = await apis.report.res(payload);
      setImage("");
      setDesc("");
      setSelectedReason(undefined);
      setIsOpen(false);
      setShowReport(false);
    } catch (error: any) {
      Toast.error(error);
    }
  };
  const toggleFavorite = async (id: string, status: boolean) => {
    try {
      const payLoad = {
        restaurant_id: id,
        status: status ? "dislike" : "favourite",
      };
      const apiRes = await apis.Favourite.toggle(payLoad);
      if (apiRes) {
        setIsFav(!status);
        Toast.success(
          status
            ? "Vendor removed from favourites"
            : "Vendor added to favourites"
        );
      }
    } catch (error) {
      Toast.error(error);
    }
  };

  const totalOrders = data?.total_orders;
  const formatted = formatOrderCount(totalOrders);

  return (
    <div className="w-full relative flex flex-col text-white h-[480px] max-sm:h-auto p-4">
      <div
        className="w-full relative flex flex-col items-center justify-center text-white bg-cover bg-center h-[445px] px-10 rounded-[30px] max-sm:h-auto max-sm:min-h-[300px] max-sm:px-4 max-sm:py-6"
        style={{
          backgroundImage: `linear-gradient(267.63deg, rgba(0, 0, 0, 0) -0.08%, rgba(0, 0, 0, 0.2) 45.76%, rgba(0, 0, 0, 0.4) 85.09%), url(${data?.image
            ? BUCKET_ROOT + data.image
            : BUCKET_ROOT + data?.uploadRestaurantPhotos?.[0]
            })`,
        }}
      >
        <div className="w-full flex justify-end h-[10%] gap-2 px-2 max-sm:gap-3 max-sm:h-auto max-sm:pb-2">
          {userInfo && (
            isFav ? (
              <div
                className="bg-white/20 backdrop-blur-sm text-white px-4 py-2 rounded-full flex items-center justify-center shadow-sm cursor-pointer mt-2"
                onClick={(e) => {
                  e.stopPropagation();
                  toggleFavorite(data._id, isFav);
                }}
              >
                <Icons.Heart />
              </div>
            ) : (
              <div
                className="bg-white/20 backdrop-blur-sm text-white px-4 py-2 rounded-full flex items-center justify-center shadow-sm cursor-pointer mt-2"
                onClick={(e) => {
                  e.stopPropagation();
                  toggleFavorite(data._id, isFav);
                }}
              >
                <Heart size={15} color="#fff" />
              </div>
            )
          )}

          <div
            className="bg-white/20 backdrop-blur-sm text-white px-4 py-2 rounded-full flex items-center justify-center shadow-sm mt-2"
            onClick={() => setShowReport(!showReport)}
          >
            <EllipsisVertical color="#fff" />
          </div>
          {showReport && (
            <div
              className=" absolute cursor-pointer h-8 p-2 bg-white text-black rounded-lg shadow-md top-10 right-2 flex flex-col gap-2 z-50"
              onClick={() => setIsOpen(true)}
            >
              Report
            </div>
          )}
        </div>
        <div className="w-full flex flex-row justify-between items-end h-[90%] px-10 pb-6 max-sm:flex-col max-sm:items-start max-sm:gap-4 max-sm:px-4 max-sm:pb-4">
          {/* Left section - Restaurant name and badges */}
          <div className="flex flex-col justify-end max-sm:items-start">
            <h1 className="text-4xl font-bold mb-4 max-sm:text-2xl max-sm:leading-tight max-sm:mb-2">
              {data?.restaurant_name}
            </h1>

            {/* Badges Row */}
            <div className="flex gap-3 max-sm:flex-wrap max-sm:gap-2">
              {/* Preparing time badge */}
              <div className="bg-white/20 backdrop-blur-sm text-white px-4 py-2 rounded-full flex items-center text-sm font-medium">
                <Clock9 size={16} className="mr-2" />
                {data?.average_preparing_time - 5}-{data?.average_preparing_time} mins
              </div>

              {/* Distance badge */}
              <div className="bg-white/20 backdrop-blur-sm text-white px-4 py-2 rounded-full flex items-center text-sm font-medium">
                <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    fillRule="evenodd"
                    d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"
                    clipRule="evenodd"
                  ></path>
                </svg>
                {distance} km • {address?.[0]}
              </div>

              {/* Rating badge */}
              {data?.rating >= 1 && (
                <div className="bg-white/20 backdrop-blur-sm text-white px-4 py-2 rounded-full flex items-center text-sm font-medium">
                  <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                  </svg>
                  {data?.rating}
                </div>
              )}

            </div>

            {/* Separator */}
            <div className="w-full h-[1px] bg-white/30 my-4"></div>

            {/* Stats Row */}
            <div className="flex gap-6 items-center max-sm:flex-wrap max-sm:gap-4">
              {formatted && (
                <div className="flex items-center gap-2">
                  <Package size={20} className="text-white" />
                  <span className="text-base font-semibold text-white">
                    {formatted} Total Orders
                  </span>
                </div>
              )}

              <div className="flex items-center gap-2">
                <Calendar size={20} className="text-white" />
                <span className="text-base font-semibold text-white">
                  Active for {calculateActiveDuration(data?.created_at)}
                </span>
              </div>
            </div>
          </div>

          {/* Right section - Operating Hours Box */}
          <div className="bg-primary rounded-xl p-5 min-w-[280px] max-sm:w-full max-sm:min-w-0">
            <div className="flex items-center gap-2 mb-3">
              <Clock9 size={20} color="#fff" />
              <h3 className="text-white font-bold text-base">We're Open From</h3>
            </div>

            {/* Time slots */}
            <div className="space-y-1">
              {getTodayTimings(data?.working_day).map((time: string, index: number) => (
                <div key={index} className="text-white text-sm font-medium pl-7">
                  • {time}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <Modal
        isOpen={isOpen}
        description=""
        onClose={() => setIsOpen(false)}
        title="Report"
      >
        <div className="w-full px-4 pt-2 pb-4 flex flex-col items-center">
          <div className="w-full mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Select Reason <span className="text-red-500">*</span>
            </label>
            <Select value={selectedReason} onValueChange={setSelectedReason}>
              <SelectTrigger className="w-full border-primary focus:ring-primary">
                <SelectValue placeholder="Choose a reason for reporting" />
              </SelectTrigger>
              <SelectContent>
                {reportReasons.map((reason: any) => (
                  <SelectItem key={reason._id} value={reason._id}>
                    {reason.reason}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          {blobFile || image ? (
            <div className="w-full mb-4">
              <CardContent className="w-full p-0">
                <div className="flex items-center justify-between border border-primary rounded-xl px-4 py-3">
                  <div className="flex items-center gap-4">
                    <img
                      src={
                        blobFile
                          ? URL.createObjectURL(blobFile)
                          : apis.BUCKET_ROOT + image
                      }
                      alt="Preview"
                      className="w-32 h-32 rounded-lg object-cover shadow"
                    />
                    <div>
                      <div className="text-sm font-semibold text-primary">
                        {fileName}
                      </div>
                    </div>
                  </div>
                  {!loading && (
                    <button
                      type="button"
                      className="text-gray-400 hover:text-red-500 transition"
                      onClick={handleClear}
                    >
                      ✖
                    </button>
                  )}
                </div>
              </CardContent>
            </div>
          ) : (
            <div
              className="w-full mb-4 flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-xl py-6 hover:border-primary transition cursor-pointer"
              onClick={handleFileSelect}
            >
              <div className="flex items-center gap-2 bg-primary/10 px-4 py-2 rounded-full">
                <Plus className="text-primary" />
                <span className="text-primary text-sm font-medium">
                  Add Image
                </span>
              </div>

              <Input
                type="file"
                accept=".jpg,.jpeg,.png"
                hidden
                ref={fileInputRef}
                onChange={handleFileChange}
                className="hidden"
              />
            </div>
          )}

          <div className="w-full mb-4 h-40">
            <Textarea
              placeholder="Enter item description..."
              value={desc}
              onChange={(e: any) => setDesc(e.target.value)}
              maxLength={120}
              className="w-full h-full resize-none text-sm p-3 rounded-md border border-gray-300 focus:outline-none focus:border-primary"
            />
          </div>

          <button
            onClick={handleReport}
            className="w-full py-3 bg-primary hover:bg-primary/90 text-white font-semibold rounded-md transition"
          >
            Submit
          </button>
        </div>
      </Modal>

    </div>
  );
};
export default RestroBanner;