'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import SidebarLayout from '../../components/sidebar-layout';
import { useTranslations } from '../../hooks/useTranslations';
import { Focus, Search, Plus, Eye, Calendar, Target } from 'lucide-react';

interface Topography {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
  };
  eye: string;
  scanDate: string;
  device: string;
  measurements: {
    simK1: number;
    simK2: number;
    simKAxis: number;
    flatK: number;
    steepK: number;
    astigmatism: number;
  };
  indices: {
    kpi: number;
    isa: number;
    sai: number;
  };
  classification: string;
}

export default function TopographyPage() {
  const { t } = useTranslations();
  const [scans, setScans] = useState<Topography[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

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

  const fetchScans = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/imaging/topography');
      if (response.ok) {
        const data = await response.json();
        setScans(data.scans || []);
      }
    } catch (error) {
      console.error('Error fetching topography:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const getClassificationBadge = (classification: string) => {
    const colors: Record<string, string> = {
      normal: 'bg-green-100 text-green-700',
      suspect: 'bg-yellow-100 text-yellow-700',
      keratoconus: 'bg-red-100 text-red-700',
      post_lasik: 'bg-blue-100 text-blue-700',
      irregular: 'bg-orange-100 text-orange-700'
    };
    return <span className={`px-2 py-1 text-xs font-medium rounded-full ${colors[classification] || 'bg-gray-100 text-gray-700'}`}>
      {classification?.replace('_', ' ')}
    </span>;
  };

  const filteredScans = scans.filter(scan =>
    scan.patientId?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    scan.patientId?.patientId?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <SidebarLayout title={t('ocularImaging.topography')} description={t('ocularImaging.topographyDescription')}>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row justify-between gap-4">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder={t('ocularImaging.searchPlaceholder')}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
            />
          </div>
          <Link
            href="/imaging/topography/new"
            className="inline-flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700"
          >
            <Plus className="h-4 w-4" />
            {t('ocularImaging.newTopography')}
          </Link>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('ocularImaging.totalScans')}</p>
                <p className="text-2xl font-bold text-gray-900">{scans.length}</p>
              </div>
              <Focus className="h-8 w-8 text-teal-600" />
            </div>
          </div>
          <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('ocularImaging.normal')}</p>
                <p className="text-2xl font-bold text-green-600">
                  {scans.filter(s => s.classification === 'normal').length}
                </p>
              </div>
              <Eye className="h-8 w-8 text-green-600" />
            </div>
          </div>
          <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('ocularImaging.keratoconus')}</p>
                <p className="text-2xl font-bold text-red-600">
                  {scans.filter(s => s.classification === 'keratoconus').length}
                </p>
              </div>
              <Target className="h-8 w-8 text-red-600" />
            </div>
          </div>
          <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('ocularImaging.thisMonth')}</p>
                <p className="text-2xl font-bold text-blue-600">
                  {scans.filter(s => {
                    const scanDate = new Date(s.scanDate);
                    const monthAgo = new Date();
                    monthAgo.setMonth(monthAgo.getMonth() - 1);
                    return scanDate >= monthAgo;
                  }).length}
                </p>
              </div>
              <Calendar className="h-8 w-8 text-blue-600" />
            </div>
          </div>
        </div>

        {/* Scans Table */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.patient')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.eye')}</th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.simK')}</th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.astigmatism')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.classification')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.date')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('ocularImaging.tableHeaders.actions')}</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {isLoading ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <tr key={i} className="animate-pulse">
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-32"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-12"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-24 mx-auto"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16 mx-auto"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-20"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-20"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                    </tr>
                  ))
                ) : filteredScans.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="px-6 py-12 text-center text-gray-500">
                      <Focus className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                      <p>{t('ocularImaging.noTopographyScans')}</p>
                      <Link href="/imaging/topography/new" className="text-teal-600 hover:text-teal-700 mt-2 inline-block">
                        {t('ocularImaging.recordFirstScan')}
                      </Link>
                    </td>
                  </tr>
                ) : (
                  filteredScans.map((scan) => (
                    <tr key={scan._id} className="hover:bg-gray-50">
                      <td className="px-6 py-4">
                        <div>
                          <p className="font-medium text-gray-900">{scan.patientId?.name}</p>
                          <p className="text-sm text-gray-500">{scan.patientId?.patientId}</p>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="font-medium text-teal-600">{scan.eye}</span>
                      </td>
                      <td className="px-6 py-4 text-center">
                        <div className="text-sm">
                          <span className="font-medium">{scan.measurements?.simK1?.toFixed(2)}</span>
                          <span className="text-gray-400 mx-1">/</span>
                          <span className="font-medium">{scan.measurements?.simK2?.toFixed(2)}</span>
                          <span className="text-gray-400 text-xs ml-1">@{scan.measurements?.simKAxis}°</span>
                        </div>
                      </td>
                      <td className="px-6 py-4 text-center">
                        <span className={`font-medium ${
                          scan.measurements?.astigmatism > 3 ? 'text-red-600' :
                          scan.measurements?.astigmatism > 1.5 ? 'text-amber-600' : 'text-green-600'
                        }`}>
                          {scan.measurements?.astigmatism?.toFixed(2)} D
                        </span>
                      </td>
                      <td className="px-6 py-4">{getClassificationBadge(scan.classification)}</td>
                      <td className="px-6 py-4 text-sm text-gray-500">
                        {new Date(scan.scanDate).toLocaleDateString()}
                      </td>
                      <td className="px-6 py-4">
                        <Link
                          href={`/imaging/topography/${scan._id}`}
                          className="text-teal-600 hover:text-teal-700 text-sm font-medium"
                        >
                          {t('ocularImaging.viewScan')}
                        </Link>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
