'use client';

import { useState } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockHouses, mockShops, mockProducts, mockMcqQuestions } from '@/lib/mock-data';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Heart,
  Building2,
  Store,
  ShoppingBag,
  GraduationCap,
  MapPin,
  Bed,
  Bath,
  Ruler,
  Star,
  ArrowRight,
  ArrowLeft,
  Trash2,
} from 'lucide-react';

type FavCategory = 'houses' | 'shops' | 'products' | 'mcq';

interface FavItem {
  id: string;
  category: FavCategory;
  data: Record<string, unknown>;
}

// Helper: avatar color from name
const avatarColors = [
  'bg-orange-500',
  'bg-emerald-500',
  'bg-orange-600',
  'bg-rose-500',
  'bg-amber-500',
  'bg-amber-600',
  'bg-orange-500',
  'bg-pink-500',
];

function getAvatarColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return avatarColors[Math.abs(hash) % avatarColors.length];
}

function getInitials(name: string): string {
  return name
    .split(' ')
    .map((n) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

// Build initial favourite items from mock data
function buildInitialFavourites(): FavItem[] {
  const items: FavItem[] = [];

  // Houses: pick first 3
  mockHouses.slice(0, 3).forEach((h) => {
    items.push({ id: `fav-h-${h.id}`, category: 'houses', data: h });
  });

  // Shops: pick first 2
  mockShops.slice(0, 2).forEach((s) => {
    items.push({ id: `fav-s-${s.id}`, category: 'shops', data: s });
  });

  // Products: pick 4
  mockProducts.slice(0, 4).forEach((p) => {
    items.push({ id: `fav-p-${p.id}`, category: 'products', data: p });
  });

  // MCQ: pick first 3 unique topics
  const seenTopics = new Set<string>();
  mockMcqQuestions.forEach((q) => {
    if (!seenTopics.has(q.topic) && items.filter((i) => i.category === 'mcq').length < 3) {
      seenTopics.add(q.topic);
      items.push({ id: `fav-q-${q.id}`, category: 'mcq', data: q });
    }
  });

  return items;
}

const categoryConfig: {
  key: FavCategory;
  labelKey: string;
  icon: React.ElementType;
  navigateSection: string;
  browseLabelKey: string;
}[] = [
  { key: 'houses', labelKey: 'fav.houses', icon: Building2, navigateSection: 'house-rental', browseLabelKey: 'house.title' },
  { key: 'shops', labelKey: 'fav.shops', icon: Store, navigateSection: 'shop-rental', browseLabelKey: 'shop.title' },
  { key: 'products', labelKey: 'fav.products', icon: ShoppingBag, navigateSection: 'marketplace', browseLabelKey: 'market.title' },
  { key: 'mcq', labelKey: 'fav.mcqTopics', icon: GraduationCap, navigateSection: 'education', browseLabelKey: 'edu.title' },
];

export default function FavouritesModule() {
  const { language, setCurrentSection } = useAppStore();
  const [activeTab, setActiveTab] = useState<FavCategory>('houses');
  const [favourites, setFavourites] = useState<FavItem[]>(buildInitialFavourites);
  const [removingId, setRemovingId] = useState<string | null>(null);

  const categoryItems = favourites.filter((f) => f.category === activeTab);

  const handleRemove = (id: string) => {
    setRemovingId(id);
    // Animate out, then remove
    setTimeout(() => {
      setFavourites((prev) => prev.filter((f) => f.id !== id));
      setRemovingId(null);
    }, 300);
  };

  const handleBrowse = (section: string) => {
    setCurrentSection(section as 'house-rental' | 'shop-rental' | 'marketplace' | 'education');
  };

  // ─── Empty State ───
  const renderEmptyState = () => {
    const config = categoryConfig.find((c) => c.key === activeTab)!;
    const Icon = config.icon;

    return (
      <div className="flex flex-col items-center justify-center px-4 py-16 text-center">
        <div className="flex h-20 w-20 items-center justify-center rounded-full bg-primary/10">
          <Heart className="h-10 w-10 text-primary/40" strokeWidth={1.5} />
        </div>
        <h3 className="mt-4 text-base font-semibold text-foreground">
          {t('fav.empty', language)}
        </h3>
        <p className="mt-1 text-sm text-muted-foreground">
          {language === 'bn'
            ? `${t(config.browseLabelKey, language)} ব্রাউজ করুন এবং পছন্দে যোগ করুন`
            : `Browse ${t(config.browseLabelKey, language)} and add to favourites`}
        </p>
        <Button
          onClick={() => handleBrowse(config.navigateSection)}
          className="mt-4 gap-2 bg-primary text-primary-foreground hover:bg-primary/90"
        >
          {language === 'bn' ? 'ব্রাউজ করুন' : `Browse ${t(config.browseLabelKey, language)}`}
          <ArrowRight className="h-4 w-4" />
        </Button>
      </div>
    );
  };

  // ─── House Card ───
  const renderHouseCard = (item: FavItem) => {
    const house = item.data as (typeof mockHouses)[number];

    return (
      <div
        key={item.id}
        className={`transition-all duration-300 ${
          removingId === item.id ? 'translate-x-8 opacity-0 scale-95' : 'translate-x-0 opacity-100 scale-100'
        }`}
      >
        <Card className="overflow-hidden py-0 gap-0">
          <div className="flex">
            {/* Color placeholder for image */}
            <div className="relative h-24 w-24 shrink-0 bg-gradient-to-br from-primary/30 to-primary/10 sm:h-28 sm:w-28">
              <div className="flex h-full w-full items-center justify-center">
                <Building2 className="h-8 w-8 text-primary/50" strokeWidth={1.5} />
              </div>
              <Badge className="absolute left-1.5 top-1.5 bg-emerald-500 text-white text-[10px] px-1.5 py-0">
                {t('house.available', language)}
              </Badge>
            </div>

            <div className="flex min-w-0 flex-1 flex-col justify-between p-3">
              <div>
                <div className="flex items-start justify-between gap-2">
                  <h3 className="truncate text-sm font-semibold text-foreground">
                    {house.title}
                  </h3>
                  <button
                    onClick={() => handleRemove(item.id)}
                    className="shrink-0 rounded-full p-1 text-primary transition-colors hover:bg-primary/10"
                    aria-label="Remove from favourites"
                  >
                    <Heart className="h-4 w-4 fill-primary" />
                  </button>
                </div>
                <div className="mt-0.5 flex items-center gap-1 text-[11px] text-muted-foreground">
                  <MapPin className="h-3 w-3" />
                  <span className="truncate">{house.upazila}, {house.district}</span>
                </div>
              </div>

              <div className="mt-2 flex items-center justify-between">
                <div className="flex items-center gap-2.5 text-[11px] text-muted-foreground">
                  <span className="flex items-center gap-0.5"><Bed className="h-3 w-3" />{house.rooms}</span>
                  <span className="flex items-center gap-0.5"><Bath className="h-3 w-3" />{house.bathrooms}</span>
                  <span className="flex items-center gap-0.5"><Ruler className="h-3 w-3" />{house.area} sqft</span>
                </div>
                <span className="text-sm font-bold text-primary">
                  ৳{house.price.toLocaleString()}<span className="text-[10px] font-normal text-muted-foreground">/mo</span>
                </span>
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  };

  // ─── Shop Card ───
  const renderShopCard = (item: FavItem) => {
    const shop = item.data as (typeof mockShops)[number];

    const shopTypeLabel: Record<string, string> = {
      retail: t('shop.retail', language),
      office: t('shop.office', language),
      warehouse: t('shop.warehouse', language),
      commercial: t('shop.commercial', language),
    };

    return (
      <div
        key={item.id}
        className={`transition-all duration-300 ${
          removingId === item.id ? 'translate-x-8 opacity-0 scale-95' : 'translate-x-0 opacity-100 scale-100'
        }`}
      >
        <Card className="overflow-hidden py-0 gap-0">
          <div className="flex">
            <div className="relative h-24 w-24 shrink-0 bg-gradient-to-br from-primary/20 to-primary/5 sm:h-28 sm:w-28">
              <div className="flex h-full w-full items-center justify-center">
                <Store className="h-8 w-8 text-primary/50" strokeWidth={1.5} />
              </div>
              <Badge className="absolute left-1.5 top-1.5 bg-primary text-white text-[10px] px-1.5 py-0">
                {shopTypeLabel[shop.shopType] || shop.shopType}
              </Badge>
            </div>

            <div className="flex min-w-0 flex-1 flex-col justify-between p-3">
              <div>
                <div className="flex items-start justify-between gap-2">
                  <h3 className="truncate text-sm font-semibold text-foreground">
                    {shop.title}
                  </h3>
                  <button
                    onClick={() => handleRemove(item.id)}
                    className="shrink-0 rounded-full p-1 text-primary transition-colors hover:bg-primary/10"
                    aria-label="Remove from favourites"
                  >
                    <Heart className="h-4 w-4 fill-primary" />
                  </button>
                </div>
                <div className="mt-0.5 flex items-center gap-1 text-[11px] text-muted-foreground">
                  <MapPin className="h-3 w-3" />
                  <span className="truncate">{shop.upazila}, {shop.district}</span>
                </div>
              </div>

              <div className="mt-2 flex items-center justify-between">
                <span className="flex items-center gap-1 text-[11px] text-muted-foreground">
                  <Ruler className="h-3 w-3" />{shop.area} sqft
                </span>
                <span className="text-sm font-bold text-primary">
                  ৳{shop.price.toLocaleString()}<span className="text-[10px] font-normal text-muted-foreground">/mo</span>
                </span>
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  };

  // ─── Product Card ───
  const renderProductCard = (item: FavItem) => {
    const product = item.data as (typeof mockProducts)[number];

    const categoryEmoji: Record<string, string> = {
      grocery: '🛒',
      electronics: '📱',
      fashion: '👗',
      medicine: '💊',
      books: '📚',
      daily_needs: '🏠',
    };

    return (
      <div
        key={item.id}
        className={`transition-all duration-300 ${
          removingId === item.id ? 'scale-90 opacity-0' : 'scale-100 opacity-100'
        }`}
      >
        <Card className="overflow-hidden py-0 gap-0">
          {/* Product image placeholder */}
          <div className="relative h-32 bg-gradient-to-br from-primary/10 to-primary/5">
            <div className="flex h-full items-center justify-center">
              <span className="text-4xl">{categoryEmoji[product.category] || '📦'}</span>
            </div>
            {product.discount > 0 && (
              <Badge className="absolute right-2 top-2 bg-red-500 text-white text-[10px] px-1.5 py-0.5">
                -{product.discount}%
              </Badge>
            )}
            <button
              onClick={() => handleRemove(item.id)}
              className="absolute left-2 top-2 rounded-full bg-background/80 p-1.5 text-primary shadow-sm backdrop-blur-sm transition-colors hover:bg-background"
              aria-label="Remove from favourites"
            >
              <Heart className="h-3.5 w-3.5 fill-primary" />
            </button>
          </div>

          <CardContent className="p-3">
            <h3 className="truncate text-sm font-semibold text-foreground">
              {product.title}
            </h3>
            <div className="mt-1 flex items-center gap-1">
              <Star className="h-3 w-3 fill-amber-400 text-amber-400" />
              <span className="text-[11px] font-medium text-foreground">{product.rating}</span>
              <span className="text-[11px] text-muted-foreground">({product.reviewCount})</span>
            </div>
            <div className="mt-2 flex items-center justify-between">
              <div className="flex items-baseline gap-1.5">
                <span className="text-sm font-bold text-primary">
                  ৳{product.price.toLocaleString()}
                </span>
                {product.discount > 0 && (
                  <span className="text-[11px] text-muted-foreground line-through">
                    ৳{Math.round(product.price / (1 - product.discount / 100)).toLocaleString()}
                  </span>
                )}
              </div>
              <span className="text-[10px] text-muted-foreground">{product.unit}</span>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  };

  // ─── MCQ Topic Card ───
  const renderMcqCard = (item: FavItem) => {
    const mcq = item.data as (typeof mockMcqQuestions)[number];

    const difficultyColor: Record<string, string> = {
      easy: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
      medium: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
      hard: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
    };

    return (
      <div
        key={item.id}
        className={`transition-all duration-300 ${
          removingId === item.id ? 'translate-x-8 opacity-0 scale-95' : 'translate-x-0 opacity-100 scale-100'
        }`}
      >
        <Card className="overflow-hidden py-0 gap-0">
          <div className="flex items-center gap-3 p-3">
            <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/10">
              <GraduationCap className="h-6 w-6 text-primary" strokeWidth={1.5} />
            </div>

            <div className="min-w-0 flex-1">
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0">
                  <h3 className="truncate text-sm font-semibold text-foreground">
                    {mcq.topic}
                  </h3>
                  <p className="mt-0.5 truncate text-[11px] text-muted-foreground">
                    {mcq.category.toUpperCase()} • {mcq.question.slice(0, 50)}...
                  </p>
                </div>
                <button
                  onClick={() => handleRemove(item.id)}
                  className="shrink-0 rounded-full p-1 text-primary transition-colors hover:bg-primary/10"
                  aria-label="Remove from favourites"
                >
                  <Heart className="h-4 w-4 fill-primary" />
                </button>
              </div>
              <div className="mt-1.5 flex items-center gap-2">
                <Badge
                  className={`text-[10px] px-1.5 py-0 border-0 ${
                    difficultyColor[mcq.difficulty] || ''
                  }`}
                >
                  {mcq.difficulty}
                </Badge>
                <span className="text-[10px] text-muted-foreground">
                  {mcq.correctAnswer === 'A' ? mcq.optionA : mcq.correctAnswer === 'B' ? mcq.optionB : mcq.correctAnswer === 'C' ? mcq.optionC : mcq.optionD}
                </span>
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  };

  // ─── Render content based on tab ───
  const renderContent = () => {
    if (categoryItems.length === 0) {
      return renderEmptyState();
    }

    switch (activeTab) {
      case 'houses':
        return (
          <div className="space-y-3 px-4">
            {categoryItems.map((item) => renderHouseCard(item))}
          </div>
        );
      case 'shops':
        return (
          <div className="space-y-3 px-4">
            {categoryItems.map((item) => renderShopCard(item))}
          </div>
        );
      case 'products':
        return (
          <div className="grid grid-cols-2 gap-3 px-4">
            {categoryItems.map((item) => renderProductCard(item))}
          </div>
        );
      case 'mcq':
        return (
          <div className="space-y-3 px-4">
            {categoryItems.map((item) => renderMcqCard(item))}
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="flex h-[calc(100vh-8rem)] flex-col overflow-hidden">
      {/* Header */}
      <div className="border-b bg-background px-4 py-3">
        <div className="flex items-center gap-2">
          <button
            onClick={() => setCurrentSection('home')}
            className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
            aria-label="Back to home"
          >
            <ArrowLeft className="h-4 w-4" />
          </button>
          <Heart className="h-5 w-5 text-primary fill-primary" />
          <h1 className="text-xl font-bold text-foreground">{t('fav.title', language)}</h1>
        </div>
        <p className="mt-0.5 text-xs text-muted-foreground">
          {language === 'bn'
            ? `${favourites.length}টি সংরক্ষিত আইটেম`
            : `${favourites.length} saved item${favourites.length !== 1 ? 's' : ''}`}
        </p>
      </div>

      {/* Category Tabs */}
      <div className="border-b bg-background">
        <div className="flex gap-2 overflow-x-auto px-4 py-3 scrollbar-hide" style={{ scrollbarWidth: 'none' }}>
          {categoryConfig.map((cat) => {
            const Icon = cat.icon;
            const isActive = activeTab === cat.key;
            const count = favourites.filter((f) => f.category === cat.key).length;

            return (
              <button
                key={cat.key}
                onClick={() => setActiveTab(cat.key)}
                className={`flex shrink-0 items-center gap-1.5 rounded-full px-4 py-2 text-sm font-medium transition-all duration-200 ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-md'
                    : 'bg-muted text-muted-foreground hover:bg-accent hover:text-foreground'
                }`}
              >
                <Icon className="h-4 w-4" />
                <span>{t(cat.labelKey, language)}</span>
                {count > 0 && (
                  <span
                    className={`ml-0.5 flex h-5 min-w-5 items-center justify-center rounded-full text-[10px] font-bold ${
                      isActive
                        ? 'bg-primary-foreground/20 text-primary-foreground'
                        : 'bg-primary/10 text-primary'
                    }`}
                  >
                    {count}
                  </span>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Content */}
      <ScrollArea className="flex-1">
        <div className="py-4 pb-6">
          {renderContent()}
        </div>
      </ScrollArea>
    </div>
  );
}
