'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import SidebarLayout from '../../../components/sidebar-layout';
import SearchablePatientSelect from '../../../components/SearchablePatientSelect';
import { ArrowLeft, Save, Scan, User, Upload } from 'lucide-react';

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

export default function NewOCTScanPage() {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);

  const [formData, setFormData] = useState({
    eye: 'OD',
    scanType: 'macula',
    device: '',
    protocol: 'macular_cube',
    quality: 'good',
    findings: {
      centralMacularThickness: 0,
      rnflThickness: 0,
      ganglionCellThickness: 0
    },
    pathologies: [] as string[],
    interpretation: '',
    notes: ''
  });

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

  const togglePathology = (pathology: string) => {
    setFormData(prev => ({
      ...prev,
      pathologies: prev.pathologies.includes(pathology)
        ? prev.pathologies.filter(p => p !== pathology)
        : [...prev.pathologies, pathology]
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPatient) {
      alert('Please select a patient');
      return;
    }

    setIsSubmitting(true);
    try {
      const response = await fetch('/api/imaging/oct', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          patientId: selectedPatient._id,
          ...formData,
          scanDate: new Date()
        })
      });

      if (response.ok) {
        const result = await response.json();
        router.push(`/imaging/oct/${result.scan._id}`);
      } else {
        alert('Failed to save OCT scan');
      }
    } catch (error) {
      console.error('Error saving OCT scan:', error);
      alert('Failed to save OCT scan');
    } finally {
      setIsSubmitting(false);
    }
  };

  const pathologyOptions = [
    'epiretinal_membrane', 'macular_hole', 'vitreomacular_traction',
    'drusen', 'rpe_changes', 'subretinal_fluid', 'intraretinal_fluid',
    'cnv', 'pigment_epithelial_detachment', 'rnfl_thinning'
  ];

  return (
    <SidebarLayout title="New OCT Scan" description="Record OCT scan results">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <Link href="/imaging/oct" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            Back to OCT Scans
          </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" />
              Patient
            </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}</p>
                </div>
                <button type="button" onClick={() => setSelectedPatient(null)} className="text-red-600 text-sm">
                  Change
                </button>
              </div>
            ) : (
              <SearchablePatientSelect
                value=""
                onChange={handlePatientSelect}
                placeholder="Search patient by name or ID..."
                className="w-full"
              />
            )}
          </div>

          {/* Scan Details */}
          <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">
              <Scan className="h-5 w-5 text-teal-600" />
              Scan 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">Eye</label>
                <select
                  value={formData.eye}
                  onChange={(e) => setFormData(prev => ({ ...prev, eye: 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="OD">OD (Right)</option>
                  <option value="OS">OS (Left)</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-gray-600 mb-1">Scan Type</label>
                <select
                  value={formData.scanType}
                  onChange={(e) => setFormData(prev => ({ ...prev, scanType: 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="macula">Macula</option>
                  <option value="rnfl">RNFL</option>
                  <option value="optic_nerve">Optic Nerve</option>
                  <option value="anterior_segment">Anterior Segment</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-gray-600 mb-1">Device</label>
                <input
                  type="text"
                  value={formData.device}
                  onChange={(e) => setFormData(prev => ({ ...prev, device: e.target.value }))}
                  placeholder="e.g., Zeiss Cirrus"
                  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">Quality</label>
                <select
                  value={formData.quality}
                  onChange={(e) => setFormData(prev => ({ ...prev, quality: 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="excellent">Excellent</option>
                  <option value="good">Good</option>
                  <option value="fair">Fair</option>
                  <option value="poor">Poor</option>
                </select>
              </div>
            </div>
          </div>

          {/* Measurements */}
          <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">Measurements</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm text-gray-600 mb-1">Central Macular Thickness (µm)</label>
                <input
                  type="number"
                  value={formData.findings.centralMacularThickness}
                  onChange={(e) => setFormData(prev => ({
                    ...prev,
                    findings: { ...prev.findings, centralMacularThickness: parseInt(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">RNFL Thickness (µm)</label>
                <input
                  type="number"
                  value={formData.findings.rnflThickness}
                  onChange={(e) => setFormData(prev => ({
                    ...prev,
                    findings: { ...prev.findings, rnflThickness: parseInt(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">GCL Thickness (µm)</label>
                <input
                  type="number"
                  value={formData.findings.ganglionCellThickness}
                  onChange={(e) => setFormData(prev => ({
                    ...prev,
                    findings: { ...prev.findings, ganglionCellThickness: parseInt(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>
          </div>

          {/* Pathologies */}
          <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">Pathologies Detected</h2>
            <div className="flex flex-wrap gap-2">
              {pathologyOptions.map(pathology => (
                <button
                  key={pathology}
                  type="button"
                  onClick={() => togglePathology(pathology)}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                    formData.pathologies.includes(pathology)
                      ? 'bg-teal-100 border-teal-500 text-teal-700'
                      : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                  }`}
                >
                  {pathology.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                </button>
              ))}
            </div>
          </div>

          {/* Interpretation */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="mb-4">
              <label className="block text-sm text-gray-600 mb-1">Interpretation</label>
              <textarea
                value={formData.interpretation}
                onChange={(e) => setFormData(prev => ({ ...prev, interpretation: 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="Clinical interpretation of OCT findings..."
              />
            </div>
            <div>
              <label className="block text-sm text-gray-600 mb-1">Additional 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}
              />
            </div>
          </div>

          {/* Submit */}
          <div className="flex justify-end gap-4">
            <Link href="/imaging/oct" 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 || !selectedPatient}
              className="px-6 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50 flex items-center gap-2"
            >
              <Save className="h-4 w-4" />
              {isSubmitting ? 'Saving...' : 'Save OCT Scan'}
            </button>
          </div>
        </form>
      </div>
    </SidebarLayout>
  );
}
