'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Clock, CheckCircle2, AlertCircle, ChevronDown, ChevronUp } from 'lucide-react';
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { authFetch } from '@/lib/api';

async function fetchPatientPrescriptions() {
  const res = await authFetch('/api/prescriptions/patient');
  return res;
}

const statusBadges = {
  pending: (
    <Badge variant="outline" className="gap-1 border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100">
      <Clock className="h-3 w-3 text-amber-600" />
      Pending
    </Badge>
  ),
  ready: (
    <Badge variant="outline" className="gap-1 border-blue-300 bg-blue-50 text-blue-800 hover:bg-blue-100">
      <Clock className="h-3 w-3 text-blue-600" />
      Ready
    </Badge>
  ),
  fulfilled: (
    <Badge variant="outline" className="gap-1 border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100">
      <CheckCircle2 className="h-3 w-3 text-emerald-600" />
      Fulfilled
    </Badge>
  ),
  rejected: (
    <Badge variant="outline" className="gap-1 border-rose-300 bg-rose-50 text-rose-800 hover:bg-rose-100">
      <AlertCircle className="h-3 w-3 text-rose-600" />
      Rejected
    </Badge>
  )
};

export default function Prescription() {
  const { data, isLoading } = useQuery({
    queryKey: ['patient-recent-prescriptions'],
    queryFn: fetchPatientPrescriptions
  });
  const [expandedRows, setExpandedRows] = useState(new Set());

  const toggleRow = (id) => {
    const newExpandedRows = new Set(expandedRows);
    if (newExpandedRows.has(id)) {
      newExpandedRows.delete(id);
    } else {
      newExpandedRows.add(id);
    }
    setExpandedRows(newExpandedRows);
  };

  if (isLoading) return <Skeleton className="w-full h-[300px]" />;

  return (
    <div className="p-4 bg-white rounded-lg shadow">
      <h3 className="font-medium mb-4">Prescriptions</h3>
      <div className="overflow-x-auto">
        {/* Desktop Table */}
        <table className="hidden md:table min-w-full divide-y divide-gray-200">
          <thead>
            <tr>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Doctor</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Pharmacy</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Medications</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {data?.map((prescription) => (
              <tr key={prescription.id}>
                <td className="px-4 py-3 whitespace-nowrap text-sm font-mono">#{prescription.id.slice(0, 8)}</td>
                <td className="px-4 py-3 whitespace-nowrap text-sm">
                  Dr. {prescription.doctorName}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm">
                  {prescription.pharmacyName}
                </td>
                <td className="px-4 py-3 text-sm">
                  <div className="flex flex-wrap gap-1 max-w-[200px]">
                    {prescription.medicines.slice(0, 3).map((med) => (
                      <span key={med.name} className="px-2 py-1 bg-gray-100 rounded-full text-xs">
                        {med.name}
                      </span>
                    ))}
                    {prescription.medicines.length > 3 && (
                      <span className="text-xs text-gray-500">+{prescription.medicines.length - 3} more</span>
                    )}
                  </div>
                </td>
                <td className="px-4 py-3 whitespace-nowrap">
                  <div className="flex items-center gap-2">
                    {statusBadges[prescription.status]}
                  </div>
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                  {new Date(prescription.createdAt).toLocaleDateString()}
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Mobile Cards */}
        <div className="md:hidden space-y-3">
          {data?.map((prescription) => (
            <div key={prescription.id} className="border rounded-lg p-3">
              <div className="flex justify-between items-start">
                <div>
                  <div className="font-medium">#{prescription.id.slice(0, 8)}</div>
                  <div className="text-sm text-gray-600">
                    Dr. {prescription.doctorName}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {statusBadges[prescription.status]}
                  <button
                    onClick={() => toggleRow(prescription.id)}
                    className="text-gray-500 hover:text-gray-700"
                  >
                    {expandedRows.has(prescription.id) ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* Collapsible content */}
              {expandedRows.has(prescription.id) && (
                <div className="mt-3 pt-3 border-t space-y-2">
                  <div>
                    <span className="text-xs text-gray-500">Pharmacy:</span>
                    <div className="text-sm">{prescription.pharmacyName}</div>
                  </div>
                  <div>
                    <span className="text-xs text-gray-500">Medications:</span>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {prescription.medicines.map((med) => (
                        <span key={med.name} className="px-2 py-1 bg-gray-100 rounded-full text-xs">
                          {med.name}
                        </span>
                      ))}
                    </div>
                  </div>
                  <div className="text-xs text-gray-500">
                    {new Date(prescription.createdAt).toLocaleDateString()}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}