'use client';

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

interface FundusPhoto {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
  };
  eye: string;
  imageType: string;
  captureDate: string;
  quality: string;
  pathologies: string[];
  interpretation: string;
}

export default function FundusPhotosPage() {
  const { t } = useTranslations();
  const [photos, setPhotos] = useState<FundusPhoto[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [imageTypeFilter, setImageTypeFilter] = useState('all');

  useEffect(() => {
    fetchPhotos();
  }, [imageTypeFilter]);

  const fetchPhotos = async () => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams();
      if (imageTypeFilter !== 'all') params.append('imageType', imageTypeFilter);
      
      const response = await fetch(`/api/imaging/fundus?${params}`);
      if (response.ok) {
        const data = await response.json();
        setPhotos(data.photos || []);
      }
    } catch (error) {
      console.error('Error fetching fundus photos:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const getQualityColor = (quality: string) => {
    const colors: Record<string, string> = {
      excellent: 'border-green-500',
      good: 'border-blue-500',
      fair: 'border-yellow-500',
      poor: 'border-red-500'
    };
    return colors[quality] || 'border-gray-300';
  };

  const filteredPhotos = photos.filter(photo =>
    photo.patientId?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    photo.patientId?.patientId?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <SidebarLayout title={t('ocularImaging.fundus')} description={t('ocularImaging.fundusDescription')}>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row justify-between gap-4">
          <div className="flex items-center gap-4 flex-1">
            <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>
            <select
              value={imageTypeFilter}
              onChange={(e) => setImageTypeFilter(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500"
            >
              <option value="all">{t('ocularImaging.allTypes')}</option>
              <option value="color">{t('ocularImaging.color')}</option>
              <option value="red_free">{t('ocularImaging.redFree')}</option>
              <option value="faf">{t('ocularImaging.faf')}</option>
              <option value="ffa">{t('ocularImaging.ffa')}</option>
              <option value="icg">{t('ocularImaging.icg')}</option>
            </select>
          </div>
          <Link
            href="/imaging/fundus/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.newPhoto')}
          </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.totalPhotos')}</p>
                <p className="text-2xl font-bold text-gray-900">{photos.length}</p>
              </div>
              <Camera 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.withPathology')}</p>
                <p className="text-2xl font-bold text-amber-600">
                  {photos.filter(p => p.pathologies && p.pathologies.length > 0).length}
                </p>
              </div>
              <AlertTriangle className="h-8 w-8 text-amber-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.thisWeek')}</p>
                <p className="text-2xl font-bold text-blue-600">
                  {photos.filter(p => {
                    const photoDate = new Date(p.captureDate);
                    const weekAgo = new Date();
                    weekAgo.setDate(weekAgo.getDate() - 7);
                    return photoDate >= weekAgo;
                  }).length}
                </p>
              </div>
              <Calendar className="h-8 w-8 text-blue-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.today')}</p>
                <p className="text-2xl font-bold text-green-600">
                  {photos.filter(p => new Date(p.captureDate).toDateString() === new Date().toDateString()).length}
                </p>
              </div>
              <Eye className="h-8 w-8 text-green-600" />
            </div>
          </div>
        </div>

        {/* Photos Grid */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {isLoading ? (
            Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden animate-pulse">
                <div className="h-40 bg-gray-200"></div>
                <div className="p-3">
                  <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
                  <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                </div>
              </div>
            ))
          ) : filteredPhotos.length === 0 ? (
            <div className="col-span-full bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
              <Camera className="h-12 w-12 mx-auto mb-4 text-gray-300" />
              <p className="text-gray-500 mb-4">{t('ocularImaging.noFundusPhotos')}</p>
              <Link href="/imaging/fundus/new" className="text-teal-600 hover:text-teal-700">
                {t('ocularImaging.captureFirstPhoto')}
              </Link>
            </div>
          ) : (
            filteredPhotos.map((photo) => (
              <Link
                key={photo._id}
                href={`/imaging/fundus/${photo._id}`}
                className={`bg-white rounded-xl shadow-sm border-2 overflow-hidden hover:shadow-md transition-shadow ${getQualityColor(photo.quality)}`}
              >
                <div className="h-40 bg-gradient-to-br from-orange-900 to-red-900 flex items-center justify-center relative">
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="w-24 h-24 rounded-full border-2 border-orange-700 opacity-50"></div>
                    <div className="absolute w-8 h-8 rounded-full bg-yellow-600 opacity-30"></div>
                  </div>
                  <Camera className="h-10 w-10 text-orange-300 opacity-50 relative z-10" />
                </div>
                <div className="p-3">
                  <div className="flex items-start justify-between mb-1">
                    <p className="font-medium text-gray-900 text-sm truncate">{photo.patientId?.name}</p>
                    <span className="text-xs font-medium text-teal-600 ml-2">{photo.eye}</span>
                  </div>
                  <p className="text-xs text-gray-500 mb-1">{photo.patientId?.patientId}</p>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-gray-400 capitalize">{photo.imageType?.replace('_', ' ')}</span>
                    {photo.pathologies && photo.pathologies.length > 0 && (
                      <span className="text-xs bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded">
                        {photo.pathologies.length} findings
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-gray-400 mt-1">
                    {new Date(photo.captureDate).toLocaleDateString()}
                  </p>
                </div>
              </Link>
            ))
          )}
        </div>
      </div>
    </SidebarLayout>
  );
}
