'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import SidebarLayout from '../components/sidebar-layout';
import { useTranslations } from '../hooks/useTranslations';
import { 
  Glasses, 
  Plus, 
  Search, 
  Filter, 
  Eye,
  Calendar,
  User,
  CheckCircle,
  Clock,
  XCircle,
  ChevronRight,
  Download
} from 'lucide-react';

interface Prescription {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
  };
  doctorId: {
    name: string;
  };
  prescriptionDate: string;
  expiryDate: string;
  prescriptionType: string;
  rightEye: {
    sphere: number;
    cylinder: number;
    axis: number;
    add: number;
  };
  leftEye: {
    sphere: number;
    cylinder: number;
    axis: number;
    add: number;
  };
  status: string;
}

export default function PrescriptionsPage() {
  const { t } = useTranslations();
  const [prescriptions, setPrescriptions] = useState<Prescription[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [typeFilter, setTypeFilter] = useState('all');

  useEffect(() => {
    fetchPrescriptions();
  }, [statusFilter, typeFilter]);

  const fetchPrescriptions = async () => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams();
      if (statusFilter !== 'all') params.append('status', statusFilter);
      if (typeFilter !== 'all') params.append('type', typeFilter);
      
      const response = await fetch(`/api/prescriptions?${params}`);
      if (response.ok) {
        const data = await response.json();
        setPrescriptions(data.prescriptions || []);
      }
    } catch (error) {
      console.error('Error fetching prescriptions:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const formatRx = (eye: any) => {
    if (!eye) return '-';
    const sph = eye.sphere >= 0 ? `+${eye.sphere.toFixed(2)}` : eye.sphere.toFixed(2);
    const cyl = eye.cylinder >= 0 ? `+${eye.cylinder.toFixed(2)}` : eye.cylinder.toFixed(2);
    return `${sph} / ${cyl} x ${eye.axis}°`;
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'issued':
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-700 flex items-center gap-1"><CheckCircle className="h-3 w-3" /> {t('opticalPrescription.status.issued')}</span>;
      case 'dispensed':
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-700 flex items-center gap-1"><Glasses className="h-3 w-3" /> {t('opticalPrescription.status.dispensed')}</span>;
      case 'expired':
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-700 flex items-center gap-1"><XCircle className="h-3 w-3" /> {t('opticalPrescription.status.expired')}</span>;
      default:
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-700">{status}</span>;
    }
  };

  const filteredPrescriptions = prescriptions.filter(rx =>
    rx.patientId?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    rx.patientId?.patientId?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <SidebarLayout title={t('opticalPrescription.title')} description={t('opticalPrescription.description')}>
      <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">
            <div className="relative flex-1 min-w-[300px]">
              <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('opticalPrescription.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 focus:border-transparent"
              />
            </div>
          </div>
          <Link
            href="/prescriptions/new"
            className="inline-flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors"
          >
            <Plus className="h-4 w-4" />
            {t('opticalPrescription.newPrescription')}
          </Link>
        </div>

        {/* Filters */}
        <div className="flex flex-wrap gap-4">
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(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('opticalPrescription.filters.allStatus')}</option>
            <option value="issued">{t('opticalPrescription.status.issued')}</option>
            <option value="dispensed">{t('opticalPrescription.status.dispensed')}</option>
            <option value="expired">{t('opticalPrescription.status.expired')}</option>
          </select>
          <select
            value={typeFilter}
            onChange={(e) => setTypeFilter(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('opticalPrescription.filters.allTypes')}</option>
            <option value="spectacles">{t('opticalPrescription.types.spectacles')}</option>
            <option value="contact_lens">{t('opticalPrescription.types.contactLens')}</option>
            <option value="both">{t('opticalPrescription.types.both')}</option>
          </select>
        </div>

        {/* Quick 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('opticalPrescription.stats.totalPrescriptions')}</p>
                <p className="text-2xl font-bold text-gray-900">{prescriptions.length}</p>
              </div>
              <Glasses 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('opticalPrescription.stats.active')}</p>
                <p className="text-2xl font-bold text-green-600">
                  {prescriptions.filter(rx => rx.status === 'issued').length}
                </p>
              </div>
              <CheckCircle 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('opticalPrescription.stats.dispensed')}</p>
                <p className="text-2xl font-bold text-blue-600">
                  {prescriptions.filter(rx => rx.status === 'dispensed').length}
                </p>
              </div>
              <Glasses 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('opticalPrescription.stats.expired')}</p>
                <p className="text-2xl font-bold text-red-600">
                  {prescriptions.filter(rx => rx.status === 'expired').length}
                </p>
              </div>
              <XCircle className="h-8 w-8 text-red-600" />
            </div>
          </div>
        </div>

        {/* Prescriptions List */}
        <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 tracking-wider">{t('opticalPrescription.tableHeaders.patient')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.tableHeaders.type')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.tableHeaders.odRight')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.tableHeaders.osLeft')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.tableHeaders.date')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.tableHeaders.expiry')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.tableHeaders.status')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{t('opticalPrescription.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-20"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-28"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-28"></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>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                    </tr>
                  ))
                ) : filteredPrescriptions.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="px-6 py-12 text-center text-gray-500">
                      <Glasses className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                      <p>{t('opticalPrescription.noResults')}</p>
                      <Link href="/prescriptions/new" className="text-teal-600 hover:text-teal-700 mt-2 inline-block">
                        {t('opticalPrescription.noResultsAdd')}
                      </Link>
                    </td>
                  </tr>
                ) : (
                  filteredPrescriptions.map((rx) => (
                    <tr key={rx._id} className="hover:bg-gray-50">
                      <td className="px-6 py-4">
                        <div>
                          <p className="font-medium text-gray-900">{rx.patientId?.name}</p>
                          <p className="text-sm text-gray-500">{rx.patientId?.patientId}</p>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="capitalize text-sm">{rx.prescriptionType?.replace('_', ' ')}</span>
                      </td>
                      <td className="px-6 py-4 font-mono text-sm">{formatRx(rx.rightEye)}</td>
                      <td className="px-6 py-4 font-mono text-sm">{formatRx(rx.leftEye)}</td>
                      <td className="px-6 py-4 text-sm text-gray-500">
                        {new Date(rx.prescriptionDate).toLocaleDateString()}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-500">
                        {new Date(rx.expiryDate).toLocaleDateString()}
                      </td>
                      <td className="px-6 py-4">{getStatusBadge(rx.status)}</td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <Link
                            href={`/prescriptions/${rx._id}`}
                            className="text-teal-600 hover:text-teal-700"
                          >
                            {t('common.view')}
                          </Link>
                          <button className="text-gray-400 hover:text-gray-600">
                            <Download className="h-4 w-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
