'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import SidebarLayout from '../../../components/sidebar-layout';
import SearchablePatientSelect from '../../../components/SearchablePatientSelect';
import { useTranslations } from '../../../hooks/useTranslations';
import { useFormatCurrency } from '../../../hooks/useFormatCurrency';
import toast from 'react-hot-toast';
import { 
  ArrowLeft, 
  Save, 
  User, 
  Glasses, 
  Eye,
  Package,
  DollarSign,
  Truck
} from 'lucide-react';

interface Patient {
  _id: string;
  name: string;
  patientId: string;
  email: string;
  phone: string;
}

interface Prescription {
  _id: string;
  prescriptionNumber: string;
  type: string;
  prescriptionDate: string;
  expiryDate: string;
  status: string;
  spectacles?: {
    OD?: { sphere?: number; cylinder?: number; axis?: number; add?: number };
    OS?: { sphere?: number; cylinder?: number; axis?: number; add?: number };
    PD?: number;
  };
}

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

const COATING_OPTIONS = [
  { value: 'Anti-Reflective', key: 'antiReflective' },
  { value: 'Blue Light Filter', key: 'blueLight' },
  { value: 'Scratch Resistant', key: 'scratchResistant' },
  { value: 'UV Protection', key: 'uvProtection' },
  { value: 'Photochromic', key: 'photochromic' },
  { value: 'Hydrophobic', key: 'hydrophobic' },
  { value: 'Oleophobic', key: 'oleophobic' }
];

export default function NewOpticalOrderPage() {
  const router = useRouter();
  const { t } = useTranslations();
  const formatCurrency = useFormatCurrency();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
  const [prescriptions, setPrescriptions] = useState<Prescription[]>([]);
  const [frames, setFrames] = useState<Frame[]>([]);
  const [loadingPrescriptions, setLoadingPrescriptions] = useState(false);
  const [activeTab, setActiveTab] = useState<'spectacles' | 'lenses' | 'payment' | 'delivery'>('spectacles');

  const [formData, setFormData] = useState({
    prescriptionId: '',
    orderType: 'spectacles' as 'spectacles' | 'contactLens' | 'both',
    frameId: '',
    frameDetails: {
      brand: '',
      model: '',
      color: '',
      size: '',
      price: 0
    },
    lensType: 'single',
    lensMaterial: 'cr39',
    lensCoatings: [] as string[],
    lensTint: 'clear',
    lensPrice: 0,
    fittingAdjustments: '',
    labInstructions: '',
    discount: 0,
    discountType: 'fixed' as 'percentage' | 'fixed',
    discountReason: '',
    paymentMethod: 'cash' as 'cash' | 'card' | 'insurance' | 'mixed',
    amountPaid: 0,
    deliveryMethod: 'pickup' as 'pickup' | 'delivery' | 'courier',
    deliveryAddress: '',
    notes: ''
  });

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

  useEffect(() => {
    if (selectedPatient) {
      fetchPrescriptions(selectedPatient._id);
    }
  }, [selectedPatient]);

  const fetchPrescriptions = async (patientId: string) => {
    try {
      setLoadingPrescriptions(true);
      const response = await fetch(`/api/prescriptions?patientId=${patientId}&status=issued`);
      if (response.ok) {
        const data = await response.json();
        setPrescriptions(data.prescriptions || []);
      }
    } catch (error) {
      console.error('Error fetching prescriptions:', error);
    } finally {
      setLoadingPrescriptions(false);
    }
  };

  const fetchFrames = async () => {
    try {
      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);
    }
  };

  const handlePatientSelect = (patient: Patient | null) => {
    setSelectedPatient(patient);
    setFormData(prev => ({ ...prev, prescriptionId: '' }));
    setPrescriptions([]);
  };

  const handleFrameSelect = (frameId: string) => {
    const frame = frames.find(f => f._id === frameId);
    if (frame) {
      setFormData(prev => ({
        ...prev,
        frameId,
        frameDetails: {
          brand: frame.brand,
          model: frame.model,
          color: frame.color,
          size: `${frame.size.eye}-${frame.size.bridge}-${frame.size.temple}`,
          price: frame.sellingPrice
        }
      }));
    }
  };

  const handleCoatingToggle = (coating: string) => {
    setFormData(prev => ({
      ...prev,
      lensCoatings: prev.lensCoatings.includes(coating)
        ? prev.lensCoatings.filter(c => c !== coating)
        : [...prev.lensCoatings, coating]
    }));
  };

  const calculateTotal = () => {
    const framePrice = formData.frameDetails.price || 0;
    const lensPrice = formData.lensPrice || 0;
    const subtotal = framePrice + lensPrice;
    const discountAmount = formData.discountType === 'percentage' 
      ? (subtotal * formData.discount / 100) 
      : formData.discount;
    return Math.max(0, subtotal - discountAmount);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!selectedPatient) {
      toast.error(t('opticalShop.newOrderPage.selectPatientError'));
      return;
    }
    if (!formData.prescriptionId) {
      toast.error(t('opticalShop.newOrderPage.selectPrescriptionError'));
      return;
    }

    setIsSubmitting(true);
    try {
      const total = calculateTotal();
      
      const orderData = {
        patientId: selectedPatient._id,
        prescriptionId: formData.prescriptionId,
        orderType: formData.orderType,
        spectacleOrder: formData.orderType !== 'contactLens' ? {
          frameId: formData.frameId || undefined,
          frameDetails: formData.frameDetails,
          lensOD: {
            type: formData.lensType,
            material: formData.lensMaterial,
            coatings: formData.lensCoatings,
            tint: formData.lensTint,
            price: formData.lensPrice / 2
          },
          lensOS: {
            type: formData.lensType,
            material: formData.lensMaterial,
            coatings: formData.lensCoatings,
            tint: formData.lensTint,
            price: formData.lensPrice / 2
          },
          fittingAdjustments: formData.fittingAdjustments,
          labInstructions: formData.labInstructions
        } : undefined,
        pricing: {
          framePrice: formData.frameDetails.price,
          lensPrice: formData.lensPrice,
          contactLensPrice: 0,
          fittingFee: 0,
          discount: formData.discount,
          discountType: formData.discountType,
          discountReason: formData.discountReason,
          tax: 0,
          total
        },
        payment: {
          method: formData.paymentMethod,
          amountPaid: formData.amountPaid,
          balance: total - formData.amountPaid
        },
        delivery: {
          method: formData.deliveryMethod,
          address: formData.deliveryAddress,
          deliveryCharge: 0
        },
        notes: formData.notes
      };
      
      const response = await fetch('/api/optical-shop/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(orderData)
      });

      if (response.ok) {
        const result = await response.json();
        router.push(`/optical-shop/orders/${result.order._id}`);
      } else {
        const err = await response.json();
        const message = err.details || err.error || t('opticalShop.newOrderPage.createFailed');
        toast.error(message);
      }
    } catch (error) {
      console.error('Error creating order:', error);
      toast.error(t('opticalShop.newOrderPage.createFailed'));
    } finally {
      setIsSubmitting(false);
    }
  };

  const lensTypes = [
    { value: 'single', labelKey: 'opticalShop.newOrderPage.lensTypes.single' },
    { value: 'bifocal', labelKey: 'opticalShop.newOrderPage.lensTypes.bifocal' },
    { value: 'progressive', labelKey: 'opticalShop.newOrderPage.lensTypes.progressive' },
    { value: 'occupational', labelKey: 'opticalShop.newOrderPage.lensTypes.occupational' }
  ];

  const lensMaterials = [
    { value: 'cr39', labelKey: 'opticalShop.newOrderPage.lensMaterials.cr39' },
    { value: 'polycarbonate', labelKey: 'opticalShop.newOrderPage.lensMaterials.polycarbonate' },
    { value: 'trivex', labelKey: 'opticalShop.newOrderPage.lensMaterials.trivex' },
    { value: 'hiIndex157', labelKey: 'opticalShop.newOrderPage.lensMaterials.hiIndex157' },
    { value: 'hiIndex160', labelKey: 'opticalShop.newOrderPage.lensMaterials.hiIndex160' },
    { value: 'hiIndex167', labelKey: 'opticalShop.newOrderPage.lensMaterials.hiIndex167' },
    { value: 'hiIndex174', labelKey: 'opticalShop.newOrderPage.lensMaterials.hiIndex174' }
  ];

  const orderTypeOptions = [
    { value: 'spectacles', labelKey: 'opticalShop.newOrderPage.spectaclesOnly', icon: Glasses },
    { value: 'contactLens', labelKey: 'opticalShop.newOrderPage.contactLenses', icon: Eye },
    { value: 'both', labelKey: 'opticalShop.newOrderPage.both', icon: Package }
  ];

  const tabs = [
    { id: 'spectacles', labelKey: 'opticalShop.newOrderPage.frameAndLens', icon: Glasses },
    { id: 'payment', labelKey: 'opticalShop.newOrderPage.payment', icon: DollarSign },
    { id: 'delivery', labelKey: 'opticalShop.newOrderPage.delivery', icon: Truck }
  ];

  const deliveryOptions = [
    { value: 'pickup', labelKey: 'opticalShop.newOrderPage.storePickup' },
    { value: 'delivery', labelKey: 'opticalShop.newOrderPage.homeDelivery' },
    { value: 'courier', labelKey: 'opticalShop.newOrderPage.courierService' }
  ];

  return (
    <SidebarLayout title={t('opticalShop.newOrderPage.title')} description={t('opticalShop.newOrderPage.description')}>
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <Link href="/optical-shop" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            {t('opticalShop.newOrderPage.backToOpticalShop')}
          </Link>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Patient Selection */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <User className="h-5 w-5 text-teal-600" />
              {t('opticalShop.newOrderPage.patientInformation')}
            </h2>

            {selectedPatient ? (
              <div className="flex items-center justify-between p-4 bg-teal-50 rounded-lg mb-4">
                <div>
                  <p className="font-medium text-gray-900">{selectedPatient.name}</p>
                  <p className="text-sm text-gray-500">ID: {selectedPatient.patientId} | {selectedPatient.phone}</p>
                </div>
                <button type="button" onClick={() => handlePatientSelect(null)} className="text-red-600 text-sm">
                  {t('opticalShop.newOrderPage.change')}
                </button>
              </div>
            ) : (
              <SearchablePatientSelect
                value=""
                onChange={handlePatientSelect}
                placeholder={t('opticalShop.newOrderPage.searchPatientPlaceholder')}
                className="w-full mb-4"
              />
            )}

            {selectedPatient && (
              <div>
                <label className="block text-sm text-gray-600 mb-1">
                  {t('opticalShop.newOrderPage.prescription')} <span className="text-red-500">*</span>
                </label>
                {loadingPrescriptions ? (
                  <p className="text-gray-500">{t('opticalShop.newOrderPage.loadingPrescriptions')}</p>
                ) : prescriptions.length === 0 ? (
                  <div className="p-4 bg-yellow-50 rounded-lg">
                    <p className="text-yellow-800">{t('opticalShop.newOrderPage.noPrescriptionsFound')}</p>
                    <Link href="/prescriptions/new" className="text-teal-600 hover:text-teal-700 text-sm font-medium">
                      {t('opticalShop.newOrderPage.createNewPrescription')}
                    </Link>
                  </div>
                ) : (
                  <select
                    value={formData.prescriptionId}
                    onChange={(e) => setFormData(prev => ({ ...prev, prescriptionId: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    required
                  >
                    <option value="">{t('opticalShop.newOrderPage.selectPrescription')}</option>
                    {prescriptions.map(rx => (
                      <option key={rx._id} value={rx._id}>
                        {rx.prescriptionNumber} - {rx.type} ({new Date(rx.prescriptionDate).toLocaleDateString()})
                      </option>
                    ))}
                  </select>
                )}
              </div>
            )}
          </div>

          {/* Order Type */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('opticalShop.newOrderPage.orderType')}</h2>
            <div className="flex gap-4">
              {orderTypeOptions.map(option => (
                <button
                  key={option.value}
                  type="button"
                  onClick={() => setFormData(prev => ({ ...prev, orderType: option.value as typeof formData.orderType }))}
                  className={`flex-1 p-4 rounded-lg border-2 transition-all ${
                    formData.orderType === option.value
                      ? 'border-teal-500 bg-teal-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <option.icon className={`h-8 w-8 mx-auto mb-2 ${
                    formData.orderType === option.value ? 'text-teal-600' : 'text-gray-400'
                  }`} />
                  <p className={`text-sm font-medium ${
                    formData.orderType === option.value ? 'text-teal-700' : 'text-gray-600'
                  }`}>
                    {t(option.labelKey)}
                  </p>
                </button>
              ))}
            </div>
          </div>

          {/* Tab Navigation */}
          {formData.orderType !== 'contactLens' && (
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="flex border-b">
                {tabs.map(tab => (
                  <button
                    key={tab.id}
                    type="button"
                    onClick={() => setActiveTab(tab.id as typeof activeTab)}
                    className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 font-medium transition-colors ${
                      activeTab === tab.id
                        ? 'text-teal-600 border-b-2 border-teal-600 bg-teal-50/50'
                        : 'text-gray-500 hover:text-gray-700'
                    }`}
                  >
                    <tab.icon className="h-4 w-4" />
                    {t(tab.labelKey)}
                  </button>
                ))}
              </div>

              <div className="p-6">
                {/* Frame & Lens Tab */}
                {activeTab === 'spectacles' && (
                  <div className="space-y-6">
                    {/* Frame Selection */}
                    <div>
                      <h3 className="font-medium text-gray-900 mb-3">{t('opticalShop.newOrderPage.selectFrame')}</h3>
                      <select
                        value={formData.frameId}
                        onChange={(e) => handleFrameSelect(e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                      >
                        <option value="">{t('opticalShop.newOrderPage.selectFrameOrOwn')}</option>
                        {frames.map(frame => (
                          <option key={frame._id} value={frame._id} disabled={frame.quantity === 0}>
                            {frame.brand} {frame.model} - {frame.color} ({formatCurrency(Number(frame.sellingPrice) || 0)}) 
                            {frame.quantity === 0 ? ` [${t('opticalShop.newOrderPage.outOfStock')}]` : ` [${frame.quantity} ${t('opticalShop.newOrderPage.inStock')}]`}
                          </option>
                        ))}
                      </select>
                      
                      {formData.frameId && (
                        <div className="mt-3 p-3 bg-gray-50 rounded-lg">
                          <p className="font-medium">{formData.frameDetails.brand} {formData.frameDetails.model}</p>
                          <p className="text-sm text-gray-500">{formData.frameDetails.color} | {t('opticalShop.fields.size')}: {formData.frameDetails.size}</p>
                          <p className="text-teal-600 font-semibold mt-1">{formatCurrency(formData.frameDetails.price)}</p>
                        </div>
                      )}
                    </div>

                    {/* Lens Type */}
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.lensType')}</label>
                        <select
                          value={formData.lensType}
                          onChange={(e) => setFormData(prev => ({ ...prev, lensType: e.target.value }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        >
                          {lensTypes.map(type => (
                            <option key={type.value} value={type.value}>{t(type.labelKey)}</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.lensMaterial')}</label>
                        <select
                          value={formData.lensMaterial}
                          onChange={(e) => setFormData(prev => ({ ...prev, lensMaterial: e.target.value }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        >
                          {lensMaterials.map(mat => (
                            <option key={mat.value} value={mat.value}>{t(mat.labelKey)}</option>
                          ))}
                        </select>
                      </div>
                    </div>

                    {/* Coatings */}
                    <div>
                      <label className="block text-sm text-gray-600 mb-2">{t('opticalShop.newOrderPage.lensCoatings')}</label>
                      <div className="flex flex-wrap gap-2">
                        {COATING_OPTIONS.map(({ value, key }) => (
                          <button
                            key={value}
                            type="button"
                            onClick={() => handleCoatingToggle(value)}
                            className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
                              formData.lensCoatings.includes(value)
                                ? 'bg-teal-100 text-teal-700 border border-teal-300'
                                : 'bg-gray-100 text-gray-600 border border-gray-200 hover:bg-gray-200'
                            }`}
                          >
                            {t(`opticalShop.newOrderPage.coatings.${key}`)}
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* Lens Price */}
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.lensPrice')}</label>
                      <input
                        type="number"
                        step="0.01"
                        value={formData.lensPrice}
                        onChange={(e) => setFormData(prev => ({ ...prev, lensPrice: parseFloat(e.target.value) || 0 }))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        placeholder="0.00"
                      />
                    </div>

                    {/* Lab Instructions */}
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.labInstructions')}</label>
                      <textarea
                        value={formData.labInstructions}
                        onChange={(e) => setFormData(prev => ({ ...prev, labInstructions: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        rows={2}
                        placeholder={t('opticalShop.newOrderPage.labInstructionsPlaceholder')}
                      />
                    </div>
                  </div>
                )}

                {/* Payment Tab */}
                {activeTab === 'payment' && (
                  <div className="space-y-6">
                    {/* Order Summary */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h3 className="font-medium text-gray-900 mb-3">{t('opticalShop.newOrderPage.orderSummary')}</h3>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-gray-600">{t('opticalShop.newOrderPage.frame')}</span>
                          <span>{formatCurrency(formData.frameDetails.price)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">{t('opticalShop.newOrderPage.lenses')}</span>
                          <span>{formatCurrency(formData.lensPrice)}</span>
                        </div>
                        {formData.discount > 0 && (
                          <div className="flex justify-between text-red-600">
                            <span>{t('opticalShop.newOrderPage.discount')} {formData.discountType === 'percentage' ? `(${formData.discount}%)` : ''}</span>
                            <span>-{formatCurrency(
                              formData.discountType === 'percentage'
                                ? ((formData.frameDetails.price + formData.lensPrice) * formData.discount / 100)
                                : formData.discount
                            )}</span>
                          </div>
                        )}
                        <div className="flex justify-between font-bold text-lg pt-2 border-t border-gray-200">
                          <span>{t('opticalShop.newOrderPage.total')}</span>
                          <span className="text-teal-600">{formatCurrency(calculateTotal())}</span>
                        </div>
                      </div>
                    </div>

                    {/* Discount */}
                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.discountType')}</label>
                        <select
                          value={formData.discountType}
                          onChange={(e) => setFormData(prev => ({ ...prev, discountType: e.target.value as 'percentage' | 'fixed' }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        >
                          <option value="fixed">{t('opticalShop.newOrderPage.fixedAmount')}</option>
                          <option value="percentage">{t('opticalShop.newOrderPage.percentage')}</option>
                        </select>
                      </div>
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">
                          {t('opticalShop.newOrderPage.discount')} {formData.discountType === 'percentage' ? '(%)' : '($)'}
                        </label>
                        <input
                          type="number"
                          step="0.01"
                          value={formData.discount}
                          onChange={(e) => setFormData(prev => ({ ...prev, discount: parseFloat(e.target.value) || 0 }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        />
                      </div>
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.discountReason')}</label>
                        <input
                          type="text"
                          value={formData.discountReason}
                          onChange={(e) => setFormData(prev => ({ ...prev, discountReason: e.target.value }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                          placeholder={t('opticalShop.newOrderPage.discountReasonPlaceholder')}
                        />
                      </div>
                    </div>

                    {/* Payment Method */}
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.paymentMethod')}</label>
                        <select
                          value={formData.paymentMethod}
                          onChange={(e) => setFormData(prev => ({ ...prev, paymentMethod: e.target.value as typeof formData.paymentMethod }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        >
                          <option value="cash">{t('opticalShop.newOrderPage.paymentMethods.cash')}</option>
                          <option value="card">{t('opticalShop.newOrderPage.paymentMethods.card')}</option>
                          <option value="insurance">{t('opticalShop.newOrderPage.paymentMethods.insurance')}</option>
                          <option value="mixed">{t('opticalShop.newOrderPage.paymentMethods.mixed')}</option>
                        </select>
                      </div>
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.amountPaid')}</label>
                        <input
                          type="number"
                          step="0.01"
                          value={formData.amountPaid}
                          onChange={(e) => setFormData(prev => ({ ...prev, amountPaid: parseFloat(e.target.value) || 0 }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        />
                      </div>
                    </div>

                    {formData.amountPaid < calculateTotal() && (
                      <div className="p-3 bg-yellow-50 rounded-lg">
                        <p className="text-yellow-800 text-sm">
                          {t('opticalShop.newOrderPage.balanceDue')}: <span className="font-bold">{formatCurrency(calculateTotal() - formData.amountPaid)}</span>
                        </p>
                      </div>
                    )}
                  </div>
                )}

                {/* Delivery Tab */}
                {activeTab === 'delivery' && (
                  <div className="space-y-6">
                    <div>
                      <label className="block text-sm text-gray-600 mb-2">{t('opticalShop.newOrderPage.deliveryMethod')}</label>
                      <div className="flex gap-4">
                        {deliveryOptions.map(option => (
                          <button
                            key={option.value}
                            type="button"
                            onClick={() => setFormData(prev => ({ ...prev, deliveryMethod: option.value as typeof formData.deliveryMethod }))}
                            className={`flex-1 p-3 rounded-lg border-2 transition-all ${
                              formData.deliveryMethod === option.value
                                ? 'border-teal-500 bg-teal-50'
                                : 'border-gray-200 hover:border-gray-300'
                            }`}
                          >
                            <p className={`text-sm font-medium ${
                              formData.deliveryMethod === option.value ? 'text-teal-700' : 'text-gray-600'
                            }`}>
                              {t(option.labelKey)}
                            </p>
                          </button>
                        ))}
                      </div>
                    </div>

                    {formData.deliveryMethod !== 'pickup' && (
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.deliveryAddress')}</label>
                        <textarea
                          value={formData.deliveryAddress}
                          onChange={(e) => setFormData(prev => ({ ...prev, deliveryAddress: e.target.value }))}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                          rows={3}
                          placeholder={t('opticalShop.newOrderPage.deliveryAddressPlaceholder')}
                        />
                      </div>
                    )}

                    <div>
                      <label className="block text-sm text-gray-600 mb-1">{t('opticalShop.newOrderPage.orderNotes')}</label>
                      <textarea
                        value={formData.notes}
                        onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                        rows={3}
                        placeholder={t('opticalShop.newOrderPage.orderNotesPlaceholder')}
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Submit */}
          <div className="flex justify-end gap-4">
            <Link 
              href="/optical-shop" 
              className="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
            >
              {t('common.cancel')}
            </Link>
            <button
              type="submit"
              disabled={isSubmitting || !selectedPatient || !formData.prescriptionId}
              className="px-6 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              <Save className="h-4 w-4" />
              {isSubmitting ? t('opticalShop.newOrderPage.creatingOrder') : t('opticalShop.newOrderPage.createOrder')}
            </button>
          </div>
        </form>
      </div>
    </SidebarLayout>
  );
}
