'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import SidebarLayout from '../../components/sidebar-layout';
import SearchablePatientSelect from '../../components/SearchablePatientSelect';
import ProtectedRoute from '../../protected-route';
import { useTranslations } from '../../hooks/useTranslations';
import toast from 'react-hot-toast';
import { 
  Glasses, 
  Save, 
  ArrowLeft,
  User,
  Eye,
  Plus,
  Minus
} from 'lucide-react';
import Link from 'next/link';

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

export default function NewPrescriptionPage() {
  const { t } = useTranslations();
  const router = useRouter();
  const { data: session } = useSession();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);

  const [formData, setFormData] = useState({
    prescriptionType: 'spectacles',
    rightEye: {
      sphere: 0,
      cylinder: 0,
      axis: 180,
      add: 0,
      pd: 32,
      prism: 0,
      prismBase: 'none'
    },
    leftEye: {
      sphere: 0,
      cylinder: 0,
      axis: 180,
      add: 0,
      pd: 32,
      prism: 0,
      prismBase: 'none'
    },
    spectacleDetails: {
      lensType: 'single_vision',
      lensMaterial: 'cr39',
      coatings: [] as string[],
      tint: 'clear',
      frameType: 'full_rim'
    },
    contactLensDetails: {
      brand: '',
      baseCurve: 8.6,
      diameter: 14.2,
      replacementSchedule: 'monthly',
      wearSchedule: 'daily_wear'
    },
    notes: '',
    expiryMonths: 12
  });

  const handlePatientSelect = (patient: Patient | null) => {
    setSelectedPatient(patient);
  };

  const updateEyeValue = (eye: 'rightEye' | 'leftEye', field: string, value: number | string) => {
    setFormData(prev => ({
      ...prev,
      [eye]: {
        ...prev[eye],
        [field]: value
      }
    }));
  };

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

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

    setIsSubmitting(true);
    try {
      const response = await fetch('/api/prescriptions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          patientId: selectedPatient._id,
          doctorId: session?.user?.id,
          ...formData
        })
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(t('opticalPrescription.createSuccess'));
        router.push(`/prescriptions/${data.prescription._id}`);
      } else {
        toast.error(data.error || t('opticalPrescription.createError'));
      }
    } catch (error) {
      console.error('Error creating prescription:', error);
      toast.error(t('opticalPrescription.createError'));
    } finally {
      setIsSubmitting(false);
    }
  };

  const sphereOptions = [];
  for (let i = -20; i <= 20; i += 0.25) {
    sphereOptions.push(i);
  }

  const cylinderOptions = [];
  for (let i = -10; i <= 0; i += 0.25) {
    cylinderOptions.push(i);
  }

  const axisOptions = [];
  for (let i = 1; i <= 180; i++) {
    axisOptions.push(i);
  }

  const addOptions = [];
  for (let i = 0; i <= 4; i += 0.25) {
    addOptions.push(i);
  }

  return (
    <ProtectedRoute>
    <SidebarLayout title={t('opticalPrescription.newPrescription')} description={t('opticalPrescription.createDescription')}>
      <div className="max-w-5xl mx-auto">
        <div className="mb-6">
          <Link href="/prescriptions" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            {t('opticalPrescription.backToPrescriptions')}
          </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('opticalPrescription.sections.patientInformation')}
            </h2>

            {selectedPatient ? (
              <div className="flex items-center justify-between p-4 bg-teal-50 rounded-lg">
                <div>
                  <p className="font-medium text-gray-900">{selectedPatient.name}</p>
                  <p className="text-sm text-gray-500">ID: {selectedPatient.patientId} {selectedPatient.dateOfBirth && `| DOB: ${new Date(selectedPatient.dateOfBirth).toLocaleDateString()}`}</p>
                </div>
                <button
                  type="button"
                  onClick={() => setSelectedPatient(null)}
                  className="text-red-600 hover:text-red-700 text-sm"
                >
                  {t('opticalPrescription.change')}
                </button>
              </div>
            ) : (
              <SearchablePatientSelect
                value=""
                onChange={handlePatientSelect}
                placeholder={t('opticalPrescription.searchPatientPlaceholder')}
                className="w-full"
              />
            )}
          </div>

          {/* Prescription 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 flex items-center gap-2">
              <Glasses className="h-5 w-5 text-teal-600" />
              {t('opticalPrescription.sections.prescriptionType')}
            </h2>

            <div className="flex gap-4">
              {['spectacles', 'contact_lens', 'both'].map(type => (
                <label
                  key={type}
                  className={`flex-1 p-4 rounded-lg border-2 cursor-pointer transition-all ${
                    formData.prescriptionType === type
                      ? 'border-teal-500 bg-teal-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <input
                    type="radio"
                    name="prescriptionType"
                    value={type}
                    checked={formData.prescriptionType === type}
                    onChange={(e) => setFormData(prev => ({ ...prev, prescriptionType: e.target.value }))}
                    className="sr-only"
                  />
                  <span className="font-medium capitalize">
                    {type === 'spectacles' ? t('opticalPrescription.types.spectacles') : 
                     type === 'contact_lens' ? t('opticalPrescription.types.contactLens') : 
                     t('opticalPrescription.types.both')}
                  </span>
                </label>
              ))}
            </div>
          </div>

          {/* Refraction Data */}
          <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">
              <Eye className="h-5 w-5 text-teal-600" />
              {t('opticalPrescription.sections.refraction')}
            </h2>

            <div className="space-y-6">
              {/* Right Eye */}
              <div>
                <h3 className="font-medium text-gray-700 mb-3">{t('opticalPrescription.sections.rightEye')}</h3>
                <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.sphere')}</label>
                    <select
                      value={formData.rightEye.sphere}
                      onChange={(e) => updateEyeValue('rightEye', 'sphere', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {sphereOptions.map(val => (
                        <option key={val} value={val}>
                          {val >= 0 ? `+${val.toFixed(2)}` : val.toFixed(2)}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.cylinder')}</label>
                    <select
                      value={formData.rightEye.cylinder}
                      onChange={(e) => updateEyeValue('rightEye', 'cylinder', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {cylinderOptions.map(val => (
                        <option key={val} value={val}>{val.toFixed(2)}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.axis')}</label>
                    <select
                      value={formData.rightEye.axis}
                      onChange={(e) => updateEyeValue('rightEye', 'axis', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {axisOptions.map(val => (
                        <option key={val} value={val}>{val}°</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.add')}</label>
                    <select
                      value={formData.rightEye.add}
                      onChange={(e) => updateEyeValue('rightEye', 'add', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {addOptions.map(val => (
                        <option key={val} value={val}>+{val.toFixed(2)}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.pd')}</label>
                    <input
                      type="number"
                      step="0.5"
                      value={formData.rightEye.pd}
                      onChange={(e) => updateEyeValue('rightEye', 'pd', parseFloat(e.target.value))}
                      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('opticalPrescription.fields.prism')}</label>
                    <input
                      type="number"
                      step="0.25"
                      value={formData.rightEye.prism}
                      onChange={(e) => updateEyeValue('rightEye', 'prism', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    />
                  </div>
                </div>
              </div>

              {/* Left Eye */}
              <div>
                <h3 className="font-medium text-gray-700 mb-3">{t('opticalPrescription.sections.leftEye')}</h3>
                <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.sphere')}</label>
                    <select
                      value={formData.leftEye.sphere}
                      onChange={(e) => updateEyeValue('leftEye', 'sphere', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {sphereOptions.map(val => (
                        <option key={val} value={val}>
                          {val >= 0 ? `+${val.toFixed(2)}` : val.toFixed(2)}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.cylinder')}</label>
                    <select
                      value={formData.leftEye.cylinder}
                      onChange={(e) => updateEyeValue('leftEye', 'cylinder', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {cylinderOptions.map(val => (
                        <option key={val} value={val}>{val.toFixed(2)}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.axis')}</label>
                    <select
                      value={formData.leftEye.axis}
                      onChange={(e) => updateEyeValue('leftEye', 'axis', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {axisOptions.map(val => (
                        <option key={val} value={val}>{val}°</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.add')}</label>
                    <select
                      value={formData.leftEye.add}
                      onChange={(e) => updateEyeValue('leftEye', 'add', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    >
                      {addOptions.map(val => (
                        <option key={val} value={val}>+{val.toFixed(2)}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.pd')}</label>
                    <input
                      type="number"
                      step="0.5"
                      value={formData.leftEye.pd}
                      onChange={(e) => updateEyeValue('leftEye', 'pd', parseFloat(e.target.value))}
                      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('opticalPrescription.fields.prism')}</label>
                    <input
                      type="number"
                      step="0.25"
                      value={formData.leftEye.prism}
                      onChange={(e) => updateEyeValue('leftEye', 'prism', parseFloat(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Spectacle Details */}
          {(formData.prescriptionType === 'spectacles' || formData.prescriptionType === 'both') && (
            <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('opticalPrescription.sections.spectacleDetails')}</h2>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <div>
                  <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.lensType')}</label>
                  <select
                    value={formData.spectacleDetails.lensType}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      spectacleDetails: { ...prev.spectacleDetails, lensType: 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="single_vision">{t('opticalPrescription.lensTypes.singleVision')}</option>
                    <option value="bifocal">{t('opticalPrescription.lensTypes.bifocal')}</option>
                    <option value="progressive">{t('opticalPrescription.lensTypes.progressive')}</option>
                    <option value="office">{t('opticalPrescription.lensTypes.office')}</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.lensMaterial')}</label>
                  <select
                    value={formData.spectacleDetails.lensMaterial}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      spectacleDetails: { ...prev.spectacleDetails, lensMaterial: 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="cr39">{t('opticalPrescription.lensMaterials.cr39')}</option>
                    <option value="polycarbonate">{t('opticalPrescription.lensMaterials.polycarbonate')}</option>
                    <option value="trivex">{t('opticalPrescription.lensMaterials.trivex')}</option>
                    <option value="hi_index_1.67">{t('opticalPrescription.lensMaterials.hiIndex167')}</option>
                    <option value="hi_index_1.74">{t('opticalPrescription.lensMaterials.hiIndex174')}</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.frameType')}</label>
                  <select
                    value={formData.spectacleDetails.frameType}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      spectacleDetails: { ...prev.spectacleDetails, frameType: 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="full_rim">{t('opticalPrescription.frameTypes.fullRim')}</option>
                    <option value="half_rim">{t('opticalPrescription.frameTypes.halfRim')}</option>
                    <option value="rimless">{t('opticalPrescription.frameTypes.rimless')}</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-sm text-gray-600 mb-2">{t('opticalPrescription.fields.coatings')}</label>
                <div className="flex flex-wrap gap-2">
                  {[
                    { key: 'anti_reflective', label: t('opticalPrescription.coatingOptions.antiReflective') },
                    { key: 'blue_light', label: t('opticalPrescription.coatingOptions.blueLight') },
                    { key: 'photochromic', label: t('opticalPrescription.coatingOptions.photochromic') },
                    { key: 'scratch_resistant', label: t('opticalPrescription.coatingOptions.scratchResistant') },
                    { key: 'hydrophobic', label: t('opticalPrescription.coatingOptions.hydrophobic') },
                    { key: 'uv_protection', label: t('opticalPrescription.coatingOptions.uvProtection') }
                  ].map(coating => (
                    <button
                      key={coating.key}
                      type="button"
                      onClick={() => toggleCoating(coating.key)}
                      className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                        formData.spectacleDetails.coatings.includes(coating.key)
                          ? 'bg-teal-100 border-teal-500 text-teal-700'
                          : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                      }`}
                    >
                      {coating.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Contact Lens Details */}
          {(formData.prescriptionType === 'contact_lens' || formData.prescriptionType === 'both') && (
            <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('opticalPrescription.sections.contactLensDetails')}</h2>
              
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.brand')}</label>
                  <input
                    type="text"
                    value={formData.contactLensDetails.brand}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contactLensDetails: { ...prev.contactLensDetails, brand: e.target.value }
                    }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
                    placeholder="e.g., Acuvue Oasys"
                  />
                </div>
                <div>
                  <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.baseCurve')}</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.contactLensDetails.baseCurve}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contactLensDetails: { ...prev.contactLensDetails, baseCurve: parseFloat(e.target.value) }
                    }))}
                    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('opticalPrescription.fields.diameter')}</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.contactLensDetails.diameter}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contactLensDetails: { ...prev.contactLensDetails, diameter: parseFloat(e.target.value) }
                    }))}
                    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('opticalPrescription.fields.replacement')}</label>
                  <select
                    value={formData.contactLensDetails.replacementSchedule}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contactLensDetails: { ...prev.contactLensDetails, replacementSchedule: 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="daily">{t('opticalPrescription.replacementSchedules.daily')}</option>
                    <option value="biweekly">{t('opticalPrescription.replacementSchedules.biweekly')}</option>
                    <option value="monthly">{t('opticalPrescription.replacementSchedules.monthly')}</option>
                    <option value="quarterly">{t('opticalPrescription.replacementSchedules.quarterly')}</option>
                  </select>
                </div>
              </div>
            </div>
          )}

          {/* Notes & Validity */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.validity')}</label>
                <select
                  value={formData.expiryMonths}
                  onChange={(e) => setFormData(prev => ({ ...prev, expiryMonths: parseInt(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={6}>{t('opticalPrescription.validityOptions.6months')}</option>
                  <option value={12}>{t('opticalPrescription.validityOptions.12months')}</option>
                  <option value={24}>{t('opticalPrescription.validityOptions.24months')}</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-gray-600 mb-1">{t('opticalPrescription.fields.notes')}</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={2}
                  placeholder={t('opticalPrescription.fields.additionalNotes')}
                />
              </div>
            </div>
          </div>

          {/* Submit */}
          <div className="flex justify-end gap-4">
            <Link
              href="/prescriptions"
              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}
              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('opticalPrescription.saving') : t('opticalPrescription.savePrescription')}
            </button>
          </div>
        </form>
      </div>
    </SidebarLayout>
    </ProtectedRoute>
  );
}
