'use client';

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

export default function EditPrescriptionPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const { data: session } = useSession();
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [patientName, setPatientName] = useState('');

  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
  });

  useEffect(() => {
    const fetchPrescription = async () => {
      try {
        const response = await fetch(`/api/prescriptions/${id}`);
        if (!response.ok) throw new Error('Failed to fetch prescription');
        
        const data = await response.json();
        const rx = data.prescription;
        
        setPatientName(rx.patientId?.name || 'Unknown Patient');
        
        // Map from model format to form format
        setFormData({
          prescriptionType: rx.type === 'contactLens' ? 'contact_lens' : rx.type,
          rightEye: {
            sphere: rx.spectacles?.OD?.sphere || 0,
            cylinder: rx.spectacles?.OD?.cylinder || 0,
            axis: rx.spectacles?.OD?.axis || 180,
            add: rx.spectacles?.OD?.add || 0,
            pd: rx.spectacles?.OD?.pd || 32,
            prism: rx.spectacles?.OD?.prism || 0,
            prismBase: rx.spectacles?.OD?.prismBase || 'none'
          },
          leftEye: {
            sphere: rx.spectacles?.OS?.sphere || 0,
            cylinder: rx.spectacles?.OS?.cylinder || 0,
            axis: rx.spectacles?.OS?.axis || 180,
            add: rx.spectacles?.OS?.add || 0,
            pd: rx.spectacles?.OS?.pd || 32,
            prism: rx.spectacles?.OS?.prism || 0,
            prismBase: rx.spectacles?.OS?.prismBase || 'none'
          },
          spectacleDetails: {
            lensType: rx.spectacles?.lensType === 'single' ? 'single_vision' : rx.spectacles?.lensType || 'single_vision',
            lensMaterial: rx.spectacles?.lensMaterial || 'cr39',
            coatings: rx.spectacles?.lensCoatings || [],
            tint: rx.spectacles?.tint || 'clear',
            frameType: rx.spectacles?.frameRecommendations || 'full_rim'
          },
          contactLensDetails: {
            brand: rx.contactLens?.OD?.brand || '',
            baseCurve: rx.contactLens?.OD?.baseCurve || 8.6,
            diameter: rx.contactLens?.OD?.diameter || 14.2,
            replacementSchedule: rx.contactLens?.OD?.modality || 'monthly',
            wearSchedule: rx.contactLens?.wearingSchedule || 'daily_wear'
          },
          notes: rx.notes || '',
          expiryMonths: 12
        });
      } catch (err) {
        setError('Failed to load prescription');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPrescription();
  }, [id]);

  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();
    setIsSubmitting(true);

    try {
      // Transform form data to model format
      let type = formData.prescriptionType;
      if (type === 'contact_lens') type = 'contactLens';

      const spectacles = (type === 'spectacles' || type === 'both') ? {
        OD: {
          sphere: formData.rightEye.sphere,
          cylinder: formData.rightEye.cylinder,
          axis: formData.rightEye.axis,
          add: formData.rightEye.add,
          prism: formData.rightEye.prism,
          prismBase: formData.rightEye.prismBase !== 'none' ? formData.rightEye.prismBase : undefined,
          pd: formData.rightEye.pd
        },
        OS: {
          sphere: formData.leftEye.sphere,
          cylinder: formData.leftEye.cylinder,
          axis: formData.leftEye.axis,
          add: formData.leftEye.add,
          prism: formData.leftEye.prism,
          prismBase: formData.leftEye.prismBase !== 'none' ? formData.leftEye.prismBase : undefined,
          pd: formData.leftEye.pd
        },
        lensType: formData.spectacleDetails.lensType === 'single_vision' ? 'single' : formData.spectacleDetails.lensType,
        lensCoatings: formData.spectacleDetails.coatings,
        lensMaterial: formData.spectacleDetails.lensMaterial,
        tint: formData.spectacleDetails.tint,
        photochromic: formData.spectacleDetails.coatings.includes('photochromic'),
        frameRecommendations: formData.spectacleDetails.frameType
      } : undefined;

      const contactLens = (type === 'contactLens' || type === 'both') ? {
        OD: {
          baseCurve: formData.contactLensDetails.baseCurve,
          diameter: formData.contactLensDetails.diameter,
          power: formData.rightEye.sphere,
          cylinder: formData.rightEye.cylinder,
          axis: formData.rightEye.axis,
          brand: formData.contactLensDetails.brand,
          material: 'hydrogel',
          type: 'soft',
          modality: formData.contactLensDetails.replacementSchedule,
          wearSchedule: formData.contactLensDetails.wearSchedule
        },
        OS: {
          baseCurve: formData.contactLensDetails.baseCurve,
          diameter: formData.contactLensDetails.diameter,
          power: formData.leftEye.sphere,
          cylinder: formData.leftEye.cylinder,
          axis: formData.leftEye.axis,
          brand: formData.contactLensDetails.brand,
          material: 'hydrogel',
          type: 'soft',
          modality: formData.contactLensDetails.replacementSchedule,
          wearSchedule: formData.contactLensDetails.wearSchedule
        }
      } : undefined;

      const response = await fetch(`/api/prescriptions/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type,
          spectacles,
          contactLens,
          notes: formData.notes
        })
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Prescription updated successfully');
        router.push(`/prescriptions/${id}`);
      } else {
        toast.error(data.error || 'Failed to update prescription');
      }
    } catch (error) {
      console.error('Error updating prescription:', error);
      toast.error('Failed to update prescription');
    } 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);
  }

  if (isLoading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title="Edit Prescription" description="Loading...">
          <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600"></div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  if (error) {
    return (
      <ProtectedRoute>
        <SidebarLayout title="Edit Prescription" description="Error">
          <div className="text-center py-12">
            <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
            <p className="text-red-600">{error}</p>
            <Link href="/prescriptions" className="text-teal-600 hover:underline mt-4 inline-block">
              Back to Prescriptions
            </Link>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <SidebarLayout title="Edit Prescription" description={`Editing prescription for ${patientName}`}>
        <div className="max-w-5xl mx-auto">
          <div className="mb-6">
            <Link href={`/prescriptions/${id}`} className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
              <ArrowLeft className="h-4 w-4" />
              Back to Prescription
            </Link>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Patient Info (Read Only) */}
            <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" />
                Patient Information
              </h2>
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="font-medium text-gray-900">{patientName}</p>
                <p className="text-sm text-gray-500">Patient cannot be changed after creation</p>
              </div>
            </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" />
                Prescription Type
              </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.replace('_', ' ')}</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" />
                Refraction
              </h2>

              <div className="space-y-6">
                {/* Right Eye */}
                <div>
                  <h3 className="font-medium text-gray-700 mb-3">OD (Right Eye)</h3>
                  <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">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">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">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">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">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">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">OS (Left Eye)</h3>
                  <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">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">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">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">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">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">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">Spectacle Details</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">Lens Type</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">Single Vision</option>
                      <option value="bifocal">Bifocal</option>
                      <option value="progressive">Progressive</option>
                      <option value="office">Office Lens</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Lens Material</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">CR-39</option>
                      <option value="polycarbonate">Polycarbonate</option>
                      <option value="trivex">Trivex</option>
                      <option value="hi_index_1.67">Hi-Index 1.67</option>
                      <option value="hi_index_1.74">Hi-Index 1.74</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Frame Type</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">Full Rim</option>
                      <option value="half_rim">Half Rim</option>
                      <option value="rimless">Rimless</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-sm text-gray-600 mb-2">Coatings</label>
                  <div className="flex flex-wrap gap-2">
                    {['anti_reflective', 'blue_light', 'photochromic', 'scratch_resistant', 'hydrophobic', 'uv_protection'].map(coating => (
                      <button
                        key={coating}
                        type="button"
                        onClick={() => toggleCoating(coating)}
                        className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                          formData.spectacleDetails.coatings.includes(coating)
                            ? 'bg-teal-100 border-teal-500 text-teal-700'
                            : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                        }`}
                      >
                        {coating.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                      </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">Contact Lens Details</h2>
                
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">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">Base Curve</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">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">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">Daily</option>
                      <option value="biweekly">Bi-weekly</option>
                      <option value="monthly">Monthly</option>
                      <option value="quarterly">Quarterly</option>
                    </select>
                  </div>
                </div>
              </div>
            )}

            {/* Notes */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
              <div>
                <label className="block text-sm text-gray-600 mb-1">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={3}
                  placeholder="Additional notes..."
                />
              </div>
            </div>

            {/* Submit */}
            <div className="flex justify-end gap-4">
              <Link
                href={`/prescriptions/${id}`}
                className="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
              >
                Cancel
              </Link>
              <button
                type="submit"
                disabled={isSubmitting}
                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 ? 'Saving...' : 'Save Changes'}
              </button>
            </div>
          </form>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
