'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, Search, Plus, Package, AlertTriangle, DollarSign, Filter } from 'lucide-react';

interface Frame {
  _id: string;
  sku: string;
  brand: string;
  model: string;
  color: string;
  size: {
    eye: number;
    bridge: number;
    temple: number;
  };
  material: string;
  type: string;
  gender: string;
  costPrice: number;
  sellingPrice: number;
  quantity: number;
  reorderLevel: number;
  active: boolean;
}

export default function FramesPage() {
  const { t } = useTranslations();
  const formatCurrency = useFormatCurrency();
  const [frames, setFrames] = useState<Frame[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [brandFilter, setBrandFilter] = useState('all');
  const [stockFilter, setStockFilter] = useState('all');

  useEffect(() => {
    fetchFrames();
  }, []);

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

  const uniqueBrands = [...new Set(frames.map(f => f.brand))];

  const filteredFrames = frames.filter(frame => {
    const matchesSearch = 
      frame.brand?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      frame.model?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      frame.sku?.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesBrand = brandFilter === 'all' || frame.brand === brandFilter;
    
    const matchesStock = stockFilter === 'all' ||
      (stockFilter === 'low' && frame.quantity <= frame.reorderLevel) ||
      (stockFilter === 'out' && frame.quantity === 0) ||
      (stockFilter === 'in' && frame.quantity > frame.reorderLevel);

    return matchesSearch && matchesBrand && matchesStock;
  });

  const stats = {
    total: frames.length,
    lowStock: frames.filter(f => f.quantity <= f.reorderLevel && f.quantity > 0).length,
    outOfStock: frames.filter(f => f.quantity === 0).length,
    totalValue: frames.reduce((sum, f) => sum + ((f.costPrice || 0) * (f.quantity || 0)), 0)
  };

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('opticalShop.frameInventory')} description={t('opticalShop.manageFrames')}>
        <div className="space-y-6">
          {/* Header */}
          <div className="flex flex-col sm:flex-row justify-between gap-4">
            <div className="flex items-center gap-4 flex-1">
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  placeholder={t('opticalShop.searchFrames')}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                />
              </div>
            </div>
            <Link
              href="/optical-shop/frames/new"
              className="inline-flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
            >
              <Plus className="h-4 w-4" />
              {t('opticalShop.addFrame')}
            </Link>
          </div>

          {/* Filters */}
          <div className="flex flex-wrap gap-4">
            <select
              value={brandFilter}
              onChange={(e) => setBrandFilter(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
            >
              <option value="all">{t('opticalShop.allBrands')}</option>
              {uniqueBrands.map(brand => (
                <option key={brand} value={brand}>{brand}</option>
              ))}
            </select>
            <select
              value={stockFilter}
              onChange={(e) => setStockFilter(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
            >
              <option value="all">{t('opticalShop.allStock')}</option>
              <option value="in">{t('opticalShop.inStock')}</option>
              <option value="low">{t('opticalShop.lowStock')}</option>
              <option value="out">{t('opticalShop.outOfStock')}</option>
            </select>
          </div>

          {/* Stats */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500">{t('opticalShop.totalFrames')}</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.total}</p>
                </div>
                <Glasses className="h-8 w-8 text-green-600" />
              </div>
            </div>
            <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500">{t('opticalShop.lowStock')}</p>
                  <p className="text-2xl font-bold text-amber-600">{stats.lowStock}</p>
                </div>
                <AlertTriangle className="h-8 w-8 text-amber-600" />
              </div>
            </div>
            <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500">{t('opticalShop.outOfStock')}</p>
                  <p className="text-2xl font-bold text-red-600">{stats.outOfStock}</p>
                </div>
                <Package className="h-8 w-8 text-red-600" />
              </div>
            </div>
            <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500">{t('opticalShop.inventoryValue')}</p>
                  <p className="text-2xl font-bold text-green-600">{formatCurrency(stats.totalValue)}</p>
                </div>
                <DollarSign className="h-8 w-8 text-green-600" />
              </div>
            </div>
          </div>

          {/* Frames Table */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('opticalShop.tableHeaders.sku')}</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('opticalShop.tableHeaders.brand')} / {t('opticalShop.fields.model')}</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('opticalShop.fields.color')}</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('opticalShop.fields.size')}</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('opticalShop.fields.material')}</th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">{t('opticalShop.fields.costPrice')}</th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">{t('opticalShop.retail')}</th>
                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('opticalShop.stock')}</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('opticalShop.tableHeaders.actions')}</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {isLoading ? (
                    Array.from({ length: 5 }).map((_, i) => (
                      <tr key={i} className="animate-pulse">
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-20"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-32"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-24"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-20"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-12 mx-auto"></div></td>
                        <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                      </tr>
                    ))
                  ) : filteredFrames.length === 0 ? (
                    <tr>
                      <td colSpan={9} className="px-6 py-12 text-center text-gray-500">
                        <Glasses className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                        <p>{t('opticalShop.noFramesFound')}</p>
                        <Link href="/optical-shop/frames/new" className="text-green-600 hover:text-green-700 mt-2 inline-block">
                          {t('opticalShop.addFirstFrame')}
                        </Link>
                      </td>
                    </tr>
                  ) : (
                    filteredFrames.map((frame) => (
                      <tr key={frame._id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 font-mono text-sm text-gray-600">{frame.sku}</td>
                        <td className="px-6 py-4">
                          <div>
                            <p className="font-medium text-gray-900">{frame.brand}</p>
                            <p className="text-sm text-gray-500">{frame.model}</p>
                          </div>
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-600">{frame.color}</td>
                        <td className="px-6 py-4 text-sm text-gray-600">
                          {frame.size?.eye}-{frame.size?.bridge}-{frame.size?.temple}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-600 capitalize">{frame.material}</td>
                        <td className="px-6 py-4 text-sm text-gray-600 text-right">{formatCurrency(frame.costPrice || 0)}</td>
                        <td className="px-6 py-4 text-sm font-medium text-gray-900 text-right">{formatCurrency(frame.sellingPrice || 0)}</td>
                        <td className="px-6 py-4 text-center">
                          <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                            frame.quantity === 0 ? 'bg-red-100 text-red-700' :
                            frame.quantity <= frame.reorderLevel ? 'bg-amber-100 text-amber-700' :
                            'bg-green-100 text-green-700'
                          }`}>
                            {frame.quantity}
                          </span>
                        </td>
                        <td className="px-6 py-4">
                          <Link
                            href={`/optical-shop/frames/${frame._id}`}
                            className="text-green-600 hover:text-green-700 text-sm font-medium"
                          >
                            {t('common.edit')}
                          </Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
