'use client';

import { useState } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import {
  ArrowLeft,
  ChevronDown,
  ChevronUp,
  Package,
  ShoppingBag,
  Clock,
  CheckCircle2,
  Truck,
  XCircle,
  PackageCheck,
  Inbox,
} from 'lucide-react';

type OrderStatus = 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled';
type FilterTab = 'all' | OrderStatus;

interface OrderItem {
  name: string;
  qty: number;
  price: number;
}

interface Order {
  id: string;
  date: string;
  status: OrderStatus;
  items: OrderItem[];
  total: number;
}

const mockOrders: Order[] = [
  {
    id: 'ORD-2024-001',
    date: '2024-12-15',
    status: 'delivered',
    items: [
      { name: 'Basmati Rice (5kg)', qty: 2, price: 450 },
      { name: 'Organic Honey (500ml)', qty: 1, price: 550 },
    ],
    total: 1450,
  },
  {
    id: 'ORD-2024-002',
    date: '2024-12-18',
    status: 'shipped',
    items: [
      { name: 'Wireless Earbuds Pro', qty: 1, price: 2500 },
      { name: 'Smart Watch X1', qty: 1, price: 3500 },
    ],
    total: 6000,
  },
  {
    id: 'ORD-2024-003',
    date: '2024-12-20',
    status: 'pending',
    items: [
      { name: 'Cotton Saree - Traditional', qty: 1, price: 1800 },
    ],
    total: 1800,
  },
  {
    id: 'ORD-2024-004',
    date: '2024-12-21',
    status: 'confirmed',
    items: [
      { name: 'HSC Physics Guide 2025', qty: 2, price: 350 },
      { name: 'Napa Extra (10 Tablets)', qty: 3, price: 45 },
      { name: 'Detergent Powder (1kg)', qty: 1, price: 120 },
    ],
    total: 955,
  },
  {
    id: 'ORD-2024-005',
    date: '2024-12-10',
    status: 'cancelled',
    items: [
      { name: 'Wireless Earbuds Pro', qty: 1, price: 2500 },
    ],
    total: 2500,
  },
  {
    id: 'ORD-2024-006',
    date: '2024-12-22',
    status: 'pending',
    items: [
      { name: 'Smart Watch X1', qty: 1, price: 3500 },
      { name: 'Organic Honey (500ml)', qty: 2, price: 550 },
    ],
    total: 4600,
  },
];

const statusConfig: Record<
  OrderStatus,
  { color: string; icon: React.ElementType; labelKey: string }
> = {
  pending: {
    color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
    icon: Clock,
    labelKey: 'order.pending',
  },
  confirmed: {
    color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
    icon: CheckCircle2,
    labelKey: 'order.confirmed',
  },
  shipped: {
    color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
    icon: Truck,
    labelKey: 'order.shipped',
  },
  delivered: {
    color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
    icon: PackageCheck,
    labelKey: 'order.delivered',
  },
  cancelled: {
    color: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
    icon: XCircle,
    labelKey: 'order.cancelled',
  },
};

const filterTabs: { key: FilterTab; labelKey: string }[] = [
  { key: 'all', labelKey: '' }, // handled separately
  { key: 'pending', labelKey: 'order.pending' },
  { key: 'confirmed', labelKey: 'order.confirmed' },
  { key: 'shipped', labelKey: 'order.shipped' },
  { key: 'delivered', labelKey: 'order.delivered' },
  { key: 'cancelled', labelKey: 'order.cancelled' },
];

function OrderCard({ order, language }: { order: Order; language: 'en' | 'bn' }) {
  const [expanded, setExpanded] = useState(false);
  const config = statusConfig[order.status];
  const StatusIcon = config.icon;
  const itemCount = order.items.reduce((sum, item) => sum + item.qty, 0);

  return (
    <Card className="overflow-hidden transition-shadow duration-200 hover:shadow-md">
      <CardContent className="p-0">
        {/* Order Header */}
        <div className="flex items-start justify-between p-4">
          <div className="flex items-center gap-3">
            <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${
              order.status === 'delivered'
                ? 'bg-emerald-100 dark:bg-emerald-900/30'
                : order.status === 'cancelled'
                ? 'bg-red-100 dark:bg-red-900/30'
                : 'bg-accent'
            }`}>
              <Package className={`h-5 w-5 ${
                order.status === 'delivered'
                  ? 'text-emerald-600 dark:text-emerald-400'
                  : order.status === 'cancelled'
                  ? 'text-red-600 dark:text-red-400'
                  : 'text-muted-foreground'
              }`} strokeWidth={1.75} />
            </div>
            <div>
              <p className="text-sm font-semibold text-foreground">#{order.id}</p>
              <p className="text-xs text-muted-foreground">
                {new Date(order.date).toLocaleDateString(language === 'bn' ? 'bn-BD' : 'en-US', {
                  year: 'numeric',
                  month: 'short',
                  day: 'numeric',
                })}
              </p>
            </div>
          </div>
          <Badge variant="secondary" className={`border-0 text-[11px] font-medium ${config.color}`}>
            <StatusIcon className="mr-1 h-3 w-3" />
            {t(config.labelKey, language)}
          </Badge>
        </div>

        <Separator />

        {/* Order Summary */}
        <div className="flex items-center justify-between px-4 py-3">
          <div className="flex items-center gap-4 text-xs text-muted-foreground">
            <span className="flex items-center gap-1">
              <ShoppingBag className="h-3.5 w-3.5" />
              {language === 'en'
                ? `${itemCount} item${itemCount > 1 ? 's' : ''}`
                : `${itemCount} টি আইটেম`}
            </span>
            <span className="font-semibold text-foreground">
              {t('common.bdt', language)}{order.total.toLocaleString()}
            </span>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 gap-1 text-xs text-primary hover:text-primary/80"
            onClick={() => setExpanded(!expanded)}
          >
            {t('common.viewDetails', language)}
            {expanded ? (
              <ChevronUp className="h-3.5 w-3.5" />
            ) : (
              <ChevronDown className="h-3.5 w-3.5" />
            )}
          </Button>
        </div>

        {/* Expanded Details */}
        {expanded && (
          <>
            <Separator />
            <div className="bg-muted/30 p-4">
              <div className="space-y-2">
                {order.items.map((item, index) => (
                  <div key={index} className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <span className="h-1.5 w-1.5 rounded-full bg-primary/50" />
                      <span className="text-foreground">{item.name}</span>
                    </div>
                    <div className="flex items-center gap-3 text-xs text-muted-foreground">
                      <span>x{item.qty}</span>
                      <span className="font-medium text-foreground">
                        {t('common.bdt', language)}{(item.price * item.qty).toLocaleString()}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
              <Separator className="my-3" />
              <div className="flex items-center justify-between text-sm font-semibold">
                <span>{language === 'en' ? 'Total' : 'মোট'}</span>
                <span className="text-primary">
                  {t('common.bdt', language)}{order.total.toLocaleString()}
                </span>
              </div>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}

export default function OrdersModule() {
  const { language, setCurrentSection } = useAppStore();
  const [activeTab, setActiveTab] = useState<FilterTab>('all');

  const filteredOrders =
    activeTab === 'all'
      ? mockOrders
      : mockOrders.filter((order) => order.status === activeTab);

  return (
    <div className="flex min-h-[calc(100vh-8rem)] flex-col">
      {/* Header */}
      <div className="bg-gradient-to-br from-primary via-primary/90 to-primary/70 px-6 pb-6 pt-6">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0 text-primary-foreground hover:bg-primary-foreground/20">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary-foreground/20">
            <Package className="h-5 w-5 text-primary-foreground" strokeWidth={1.75} />
          </div>
          <div>
            <h1 className="text-xl font-bold text-primary-foreground">
              {t('order.title', language)}
            </h1>
            <p className="text-xs text-primary-foreground/70">
              {language === 'en' ? `${mockOrders.length} orders total` : `মোট ${mockOrders.length} টি অর্ডার`}
            </p>
          </div>
        </div>
      </div>

      {/* Filter Tabs */}
      <div className="sticky top-0 z-10 border-b bg-background px-4 py-2">
        <div className="scrollbar-hide flex gap-2 overflow-x-auto pb-1">
          <button
            onClick={() => setActiveTab('all')}
            className={`shrink-0 rounded-full px-4 py-1.5 text-xs font-medium transition-colors duration-150 ${
              activeTab === 'all'
                ? 'bg-primary text-primary-foreground shadow-sm'
                : 'bg-muted text-muted-foreground hover:bg-accent'
            }`}
          >
            {language === 'en' ? 'All' : 'সব'}
          </button>
          {filterTabs.slice(1).map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`shrink-0 rounded-full px-4 py-1.5 text-xs font-medium transition-colors duration-150 ${
                activeTab === tab.key
                  ? 'bg-primary text-primary-foreground shadow-sm'
                  : 'bg-muted text-muted-foreground hover:bg-accent'
              }`}
            >
              {t(tab.labelKey, language)}
            </button>
          ))}
        </div>
      </div>

      {/* Order List */}
      <div className="flex-1 px-4 py-4">
        {filteredOrders.length > 0 ? (
          <div className="space-y-3">
            {filteredOrders.map((order) => (
              <OrderCard key={order.id} order={order} language={language} />
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-4 py-20">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-muted">
              <Inbox className="h-8 w-8 text-muted-foreground" strokeWidth={1.5} />
            </div>
            <div className="text-center">
              <p className="text-sm font-medium text-foreground">
                {t('common.noResults', language)}
              </p>
              <p className="mt-1 text-xs text-muted-foreground">
                {language === 'en'
                  ? `No ${activeTab} orders found`
                  : `কোনো ${t(`order.${activeTab}`, language)} অর্ডার পাওয়া যায়নি`}
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
