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

interface Lens {
  _id: string;
  sku: string;
  type: string;
  material: string;
  index: number;
  coating: string[];
  brand: string;
  powerRange: {
    sphereMin: number;
    sphereMax: number;
    cylinderMin: number;
    cylinderMax: number;
  };
  costPrice: number;
  sellingPrice: number;
  quantity: number;
  reorderLevel: number;
}

export default function LensInventoryPage() {
  const { t } = useTranslations();
  const formatCurrency = useFormatCurrency();
  const [lenses, setLenses] = useState<Lens[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [materialFilter, setMaterialFilter] = useState('all');

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

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

  const uniqueTypes = [...new Set(lenses.map(l => l.type))];
  const uniqueMaterials = [...new Set(lenses.map(l => l.material))];

  const filteredLenses = lenses.filter(lens => {
    const matchesSearch = 
      lens.brand?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      lens.sku?.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesType = typeFilter === 'all' || lens.type === typeFilter;
    const matchesMaterial = materialFilter === 'all' || lens.material === materialFilter;

    return matchesSearch && matchesType && matchesMaterial;
  });

  const stats = {
    total: lenses.length,
    lowStock: lenses.filter(l => l.quantity <= l.reorderLevel && l.quantity > 0).length,
    outOfStock: lenses.filter(l => l.quantity === 0).length
  };

  const getLensTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      single_vision: 'Single Vision',
      bifocal: 'Bifocal',
      progressive: 'Progressive',
      office: 'Office',
      reading: 'Reading'
    };
    return labels[type] || type;
  };

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('opticalShop.lensInventory')} description={t('opticalShop.manageLenses')}>
        <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.searchLenses')}
                  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/lenses/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.addLens')}
            </Link>
          </div>

          {/* Filters */}
          <div className="flex flex-wrap gap-4">
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(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.allTypes')}</option>
              {uniqueTypes.map(type => (
                <option key={type} value={type}>{getLensTypeLabel(type)}</option>
              ))}
            </select>
            <select
              value={materialFilter}
              onChange={(e) => setMaterialFilter(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.allMaterials')}</option>
              {uniqueMaterials.map(material => (
                <option key={material} value={material}>{material}</option>
              ))}
            </select>
          </div>

          {/* Stats */}
          <div className="grid grid-cols-1 md:grid-cols-3 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.totalLensTypes')}</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.total}</p>
                </div>
                <CircleDot 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>

          {/* Lenses Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {isLoading ? (
              Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 animate-pulse">
                  <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
                  <div className="h-3 bg-gray-200 rounded w-1/2 mb-4"></div>
                  <div className="h-20 bg-gray-200 rounded"></div>
                </div>
              ))
            ) : filteredLenses.length === 0 ? (
              <div className="col-span-full bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
                <CircleDot className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                <p className="text-gray-500 mb-4">{t('opticalShop.noLensesFound')}</p>
                <Link href="/optical-shop/lenses/new" className="text-green-600 hover:text-green-700">
                  {t('opticalShop.addFirstLens')}
                </Link>
              </div>
            ) : (
              filteredLenses.map((lens) => (
                <div
                  key={lens._id}
                  className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div>
                      <p className="font-medium text-gray-900">{lens.brand || lens.sku}</p>
                      <p className="text-sm text-gray-500">{getLensTypeLabel(lens.type)}</p>
                    </div>
                    <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                      lens.quantity === 0 ? 'bg-red-100 text-red-700' :
                      lens.quantity <= lens.reorderLevel ? 'bg-amber-100 text-amber-700' :
                      'bg-green-100 text-green-700'
                    }`}>
                      {lens.quantity} {t('opticalShop.inStockLabel')}
                    </span>
                  </div>

                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-gray-500">{t('opticalShop.fields.material')}</span>
                      <span className="text-gray-700">{lens.material}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">{t('opticalShop.index')}</span>
                      <span className="text-gray-700">{lens.index}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">{t('opticalShop.sphereRange')}</span>
                      <span className="text-gray-700">
                        {lens.powerRange?.sphereMin} to {lens.powerRange?.sphereMax}
                      </span>
                    </div>
                    {lens.coating && lens.coating.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-2">
                        {lens.coating.map(c => (
                          <span key={c} className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">
                            {c.replace(/_/g, ' ')}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>

                  <div className="flex items-center justify-between mt-4 pt-3 border-t border-gray-100">
                    <div>
                      <span className="text-sm text-gray-500">{t('opticalShop.price')}: </span>
                      <span className="font-medium text-gray-900">{formatCurrency(lens.sellingPrice || 0)}</span>
                    </div>
                    <Link
                      href={`/optical-shop/lenses/${lens._id}`}
                      className="text-green-600 hover:text-green-700 text-sm font-medium"
                    >
                      {t('common.edit')}
                    </Link>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
