'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import SidebarLayout from '../components/sidebar-layout';
import ProtectedRoute from '../protected-route';
import { useTranslations } from '../hooks/useTranslations';
import { useFormatCurrency } from '../hooks/useFormatCurrency';
import { 
  Glasses, 
  Plus, 
  Search, 
  Package,
  ShoppingCart,
  DollarSign,
  TrendingUp,
  Eye,
  Filter,
  ChevronRight,
  Clock,
  CheckCircle,
  Truck,
  AlertTriangle
} from 'lucide-react';

interface Frame {
  _id: string;
  sku: string;
  brand: string;
  model: string;
  color: string;
  size: { eye: number; bridge: number; temple: number };
  material: string;
  sellingPrice: number;
  quantity: number;
  reorderLevel: number;
  imageUrl: string;
}

interface Order {
  _id: string;
  orderNumber: string;
  patientId: { name: string; patientId: string };
  orderType: string;
  pricing: { total: number };
  status: string;
  orderDate: string;
}

export default function OpticalShopPage() {
  const { t } = useTranslations();
  const formatCurrency = useFormatCurrency();
  const [activeTab, setActiveTab] = useState<'orders' | 'frames' | 'inventory'>('orders');
  const [frames, setFrames] = useState<Frame[]>([]);
  const [orders, setOrders] = useState<Order[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [stats, setStats] = useState({
    pending: 0,
    inProduction: 0,
    ready: 0,
    delivered: 0
  });

  useEffect(() => {
    if (activeTab === 'orders') {
      fetchOrders();
    } else {
      fetchFrames();
    }
  }, [activeTab]);

  const fetchOrders = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/optical-shop/orders');
      const data = await response.json();
      setOrders(data.orders || []);
      setStats(data.stats || { pending: 0, inProduction: 0, ready: 0, delivered: 0 });
    } catch (error) {
      console.error('Error fetching orders:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchFrames = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/optical-shop/frames');
      const data = await response.json();
      setFrames(data.frames || []);
    } catch (error) {
      console.error('Error fetching frames:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'ordered': return 'bg-blue-100 text-blue-700';
      case 'inProduction': return 'bg-yellow-100 text-yellow-700';
      case 'qualityCheck': return 'bg-purple-100 text-purple-700';
      case 'ready': return 'bg-green-100 text-green-700';
      case 'dispatched': return 'bg-indigo-100 text-indigo-700';
      case 'delivered': return 'bg-emerald-100 text-emerald-700';
      case 'cancelled': return 'bg-red-100 text-red-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const filteredFrames = frames.filter(frame => {
    if (!searchTerm) return true;
    const search = searchTerm.toLowerCase();
    return (
      frame.brand.toLowerCase().includes(search) ||
      frame.model.toLowerCase().includes(search) ||
      frame.sku.toLowerCase().includes(search)
    );
  });

  const filteredOrders = orders.filter(order => {
    if (!searchTerm) return true;
    const search = searchTerm.toLowerCase();
    return (
      order.orderNumber.toLowerCase().includes(search) ||
      order.patientId?.name?.toLowerCase().includes(search)
    );
  });

  const lowStockFrames = frames.filter(f => f.quantity <= f.reorderLevel);

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('opticalShop.title')} description={t('opticalShop.description')}>
        <div className="space-y-6">
          {/* Stats Cards */}
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-100 text-sm">{t('opticalShop.pendingOrders')}</p>
                  <p className="text-3xl font-bold mt-1">{stats.pending}</p>
                </div>
                <Clock className="h-10 w-10 text-blue-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-amber-500 to-amber-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-amber-100 text-sm">{t('opticalShop.inProduction')}</p>
                  <p className="text-3xl font-bold mt-1">{stats.inProduction}</p>
                </div>
                <Package className="h-10 w-10 text-amber-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-100 text-sm">{t('opticalShop.readyForPickup')}</p>
                  <p className="text-3xl font-bold mt-1">{stats.ready}</p>
                </div>
                <CheckCircle className="h-10 w-10 text-green-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-emerald-500 to-emerald-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-emerald-100 text-sm">{t('opticalShop.delivered')}</p>
                  <p className="text-3xl font-bold mt-1">{stats.delivered}</p>
                </div>
                <Truck className="h-10 w-10 text-emerald-200" />
              </div>
            </div>
            
            <div className={`rounded-xl p-5 text-white ${
              lowStockFrames.length > 0 
                ? 'bg-gradient-to-br from-red-500 to-red-600' 
                : 'bg-gradient-to-br from-gray-500 to-gray-600'
            }`}>
              <div className="flex items-center justify-between">
                <div>
                  <p className={`text-sm ${lowStockFrames.length > 0 ? 'text-red-100' : 'text-gray-100'}`}>
                    {t('opticalShop.lowStock')}
                  </p>
                  <p className="text-3xl font-bold mt-1">{lowStockFrames.length}</p>
                </div>
                <AlertTriangle className={`h-10 w-10 ${
                  lowStockFrames.length > 0 ? 'text-red-200' : 'text-gray-200'
                }`} />
              </div>
            </div>
          </div>

          {/* Tab Navigation */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="flex border-b">
              <button
                onClick={() => setActiveTab('orders')}
                className={`flex-1 flex items-center justify-center gap-2 px-6 py-4 font-medium transition-colors ${
                  activeTab === 'orders'
                    ? 'text-teal-600 border-b-2 border-teal-600 bg-teal-50/50'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                <ShoppingCart className="h-5 w-5" />
                {t('opticalShop.orders')}
              </button>
              <button
                onClick={() => setActiveTab('frames')}
                className={`flex-1 flex items-center justify-center gap-2 px-6 py-4 font-medium transition-colors ${
                  activeTab === 'frames'
                    ? 'text-teal-600 border-b-2 border-teal-600 bg-teal-50/50'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                <Glasses className="h-5 w-5" />
                {t('opticalShop.frames')}
              </button>
              <button
                onClick={() => setActiveTab('inventory')}
                className={`flex-1 flex items-center justify-center gap-2 px-6 py-4 font-medium transition-colors ${
                  activeTab === 'inventory'
                    ? 'text-teal-600 border-b-2 border-teal-600 bg-teal-50/50'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                <Package className="h-5 w-5" />
                {t('opticalShop.lensInventory')}
              </button>
            </div>

            {/* Search and Actions */}
            <div className="p-4 border-b border-gray-100">
              <div className="flex gap-4 items-center justify-between">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    placeholder={activeTab === 'orders' ? t('opticalShop.searchOrders') : t('opticalShop.searchFrames')}
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-teal-500"
                  />
                </div>
                
                <Link
                  href={activeTab === 'orders' ? '/optical-shop/orders/new' : '/optical-shop/frames/new'}
                  className="flex items-center gap-2 px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors font-medium"
                >
                  <Plus className="h-5 w-5" />
                  {activeTab === 'orders' ? t('opticalShop.newOrder') : t('opticalShop.addFrame')}
                </Link>
              </div>
            </div>

            {/* Content */}
            <div className="p-4">
              {isLoading ? (
                <div className="p-8 text-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600 mx-auto"></div>
                  <p className="mt-4 text-gray-500">{t('opticalShop.loading')}</p>
                </div>
              ) : activeTab === 'orders' ? (
                filteredOrders.length === 0 ? (
                  <div className="p-12 text-center">
                    <ShoppingCart className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-gray-900 mb-2">{t('opticalShop.noOrdersFound')}</h3>
                    <p className="text-gray-500 mb-6">{t('opticalShop.createFirstOrder')}</p>
                    <Link
                      href="/optical-shop/orders/new"
                      className="inline-flex items-center gap-2 px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700"
                    >
                      <Plus className="h-5 w-5" />
                      {t('opticalShop.newOrder')}
                    </Link>
                  </div>
                ) : (
                  <div className="divide-y divide-gray-100">
                    {filteredOrders.map((order) => (
                      <Link
                        key={order._id}
                        href={`/optical-shop/orders/${order._id}`}
                        className="flex items-center justify-between p-4 hover:bg-gray-50 rounded-lg transition-colors"
                      >
                        <div className="flex items-center gap-4">
                          <div className="w-12 h-12 bg-teal-100 rounded-full flex items-center justify-center">
                            <Glasses className="h-6 w-6 text-teal-600" />
                          </div>
                          <div>
                            <h3 className="font-semibold text-gray-900">{order.orderNumber}</h3>
                            <p className="text-sm text-gray-500">{order.patientId?.name}</p>
                          </div>
                        </div>
                        
                        <div className="flex items-center gap-8">
                          <div>
                            <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                              getStatusColor(order.status)
                            }`}>
                              {order.status}
                            </span>
                          </div>
                          <div className="text-right">
                            <p className="font-semibold text-gray-900">{formatCurrency(order.pricing?.total ?? 0)}</p>
                            <p className="text-sm text-gray-500">
                              {new Date(order.orderDate).toLocaleDateString()}
                            </p>
                          </div>
                          <ChevronRight className="h-5 w-5 text-gray-400" />
                        </div>
                      </Link>
                    ))}
                  </div>
                )
              ) : activeTab === 'frames' ? (
                filteredFrames.length === 0 ? (
                  <div className="p-12 text-center">
                    <Glasses className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-gray-900 mb-2">{t('opticalShop.noFramesFound')}</h3>
                    <p className="text-gray-500 mb-6">{t('opticalShop.addFramesToInventory')}</p>
                    <Link
                      href="/optical-shop/frames/new"
                      className="inline-flex items-center gap-2 px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700"
                    >
                      <Plus className="h-5 w-5" />
                      {t('opticalShop.addFrame')}
                    </Link>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredFrames.map((frame) => (
                      <Link
                        key={frame._id}
                        href={`/optical-shop/frames/${frame._id}`}
                        className="bg-white border border-gray-200 rounded-xl p-4 hover:shadow-md transition-all"
                      >
                        <div className="aspect-video bg-gray-100 rounded-lg mb-4 flex items-center justify-center">
                          {frame.imageUrl ? (
                            <img src={frame.imageUrl} alt={frame.model} className="object-contain h-full" />
                          ) : (
                            <Glasses className="h-12 w-12 text-gray-300" />
                          )}
                        </div>
                        <div>
                          <h3 className="font-semibold text-gray-900">{frame.brand}</h3>
                          <p className="text-sm text-gray-600">{frame.model}</p>
                          <p className="text-xs text-gray-500 mt-1">
                            {frame.size.eye}-{frame.size.bridge}-{frame.size.temple} | {frame.color}
                          </p>
                          <div className="flex items-center justify-between mt-3">
                            <span className="text-lg font-bold text-teal-600">
                              {formatCurrency(frame.sellingPrice)}
                            </span>
                            <span className={`px-2 py-1 rounded text-xs font-medium ${
                              frame.quantity <= frame.reorderLevel
                                ? 'bg-red-100 text-red-700'
                                : 'bg-green-100 text-green-700'
                            }`}>
                              {t('opticalShop.stock')}: {frame.quantity}
                            </span>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                )
              ) : (
                <div className="p-12 text-center">
                  <Package className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">{t('opticalShop.lensInventory')}</h3>
                  <p className="text-gray-500">{t('opticalShop.manageLensesDescription')}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
