"use client";
import {
  createContext, useContext, useState, useMemo, useCallback, type ReactNode,
} from "react";
import type { SellerProfile, NewReview } from "@/components/seller/types";
import { MOCK_SELLER } from "@/components/seller/mockData";

interface SellerContextValue {
  profile: SellerProfile;
  submitReview: (review: NewReview) => void;
  reportSeller: (reason: string, description: string) => void;
  reportListing: (listingId: string, reason: string, description: string) => void;
  toggleWishlist: (listingId: string) => void;
  toggleFollow: () => void;
}

const SellerContext = createContext<SellerContextValue | null>(null);

export function SellerProvider({ children }: { children: ReactNode }) {
  const [profile, setProfile] = useState<SellerProfile>(MOCK_SELLER);

  const submitReview = useCallback((newReview: NewReview) => {
    const listing = profile.listings.find((l) => l.id === newReview.productId);
    const review = {
      id: `r-${Date.now()}`,
      buyerId: "me",
      buyerName: "You",
      buyerAvatar: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=80&h=80&fit=crop&q=80",
      rating: newReview.rating,
      title: newReview.title,
      text: newReview.text,
      date: new Date().toISOString().split("T")[0],
      productId: newReview.productId,
      productTitle: listing?.title ?? "Your Purchase",
      productImage: listing?.image ?? "",
      helpful: 0,
      verified: true,
    };
    setProfile((prev) => ({
      ...prev,
      reviews: [review, ...prev.reviews],
      stats: {
        ...prev.stats,
        totalReviews: prev.stats.totalReviews + 1,
        averageRating: parseFloat(
          (
            (prev.stats.averageRating * prev.stats.totalReviews + newReview.rating) /
            (prev.stats.totalReviews + 1)
          ).toFixed(1)
        ),
      },
      ratingDistribution: {
        ...prev.ratingDistribution,
        [newReview.rating as 1 | 2 | 3 | 4 | 5]:
          prev.ratingDistribution[newReview.rating as 1 | 2 | 3 | 4 | 5] + 1,
      },
    }));
  }, [profile.listings]);

  const reportSeller = useCallback((_reason: string, _description: string) => {
    // Production: API call
  }, []);

  const reportListing = useCallback((_listingId: string, _reason: string, _description: string) => {
    // Production: API call
  }, []);

  const toggleWishlist = useCallback((listingId: string) => {
    setProfile((prev) => ({
      ...prev,
      listings: prev.listings.map((l) =>
        l.id === listingId ? { ...l, wishlisted: !l.wishlisted } : l
      ),
    }));
  }, []);

  const toggleFollow = useCallback(() => {
    setProfile((prev) => ({
      ...prev,
      isFollowing: !prev.isFollowing,
      stats: {
        ...prev.stats,
        followers: prev.isFollowing ? prev.stats.followers - 1 : prev.stats.followers + 1,
      },
    }));
  }, []);

  const value = useMemo(
    () => ({ profile, submitReview, reportSeller, reportListing, toggleWishlist, toggleFollow }),
    [profile, submitReview, reportSeller, reportListing, toggleWishlist, toggleFollow]
  );

  return <SellerContext.Provider value={value}>{children}</SellerContext.Provider>;
}

export function useSeller() {
  const ctx = useContext(SellerContext);
  if (!ctx) throw new Error("useSeller must be used inside SellerProvider");
  return ctx;
}
