import {
  Card,
  CardBody,
  CardHeader,
  CardFooter,
  Avatar,
  Typography,
  Tabs,
  TabsHeader,
  Tab,
  Tooltip,
  Button,
  Chip,
} from "@material-tailwind/react";
import {
  HomeIcon,
  ShieldCheckIcon,
  CalendarDaysIcon,
  PencilIcon,
  ArrowLeftIcon,
} from "@heroicons/react/24/solid";
import { MessageCard } from "@/widgets/cards";
import { useLocation, useNavigate, useParams } from "react-router-dom";

const getStatusColor = (status) => {
  switch (status) {
    case "done": return "green";
    case "pending": return "orange";
    case "overdue": return "red";
    default: return "blue-gray";
  }
};

const formatDate = (dateString) => {
  if (!dateString) return "Not administered";
  return new Date(dateString).toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
};

export function PatientDetail() {
  const { id } = useParams();
  const { state } = useLocation();
  const navigate = useNavigate();



  // Handle case when accessed directly without state
  if (!state?.patient) {
    return (
      <div className="p-4 text-center">
        <Typography variant="h4" color="blue-gray">
          Patient not found
        </Typography>
        <Button onClick={() => navigate('/patients')} className="mt-4">
          Return to patients list
        </Button>
      </div>
    );
  }

  console.log("Patient ID:", id);
  console.log("Patient State:", state);

  // Destructure data from navigation state
  const { patient, vaccinations = [], appointments = [] } = state;

  // Process patient data
  const patientData = {
    name: `${patient.firstName} ${patient.lastName}`,
    avatar: patient.img || "/img/default-avatar.jpg",
    age: patient.age || "Not specified",
    gender: patient.gender || "Not specified",
    bloodType: patient.bloodType || "Not specified",
    phone: patient.phone || patient.parent?.phone || "Not specified",
    email: patient.email || patient.parent?.email || "Not specified",
    address: patient.address || "Not specified",
    emergencyContact: patient.parent?.fullName || "Not specified",
    allergies: patient.allergies || "None specified",
    chronicConditions: patient.chronicConditions || "None specified",
  };

  // Process appointments data
  const processedAppointments = appointments.map(appointment => ({
    name: appointment.doctor || "Medical Staff",
    message: `Appointment for ${appointment.type || "check-up"}`,
    time: appointment.date ? formatDate(appointment.date) : "No date specified",
  }));


  return (
    <>
      {/* Back Button */}
      <Button 
        variant="text" 
        className="flex items-center gap-2 mt-4 ml-4"
        onClick={() => navigate(-1)}
      >
        <ArrowLeftIcon className="h-5 w-5" />
        Back
      </Button>

      <div className="relative mt-4 h-72 w-full overflow-hidden rounded-xl bg-[url('/img/background-image.png')] bg-cover bg-center">
        <div className="absolute inset-0 h-full w-full bg-gray-900/75" />
      </div>

      <Card className="mx-3 -mt-16 mb-6 lg:mx-4 border border-blue-gray-100">
        <CardBody className="p-4">
          <div className="mb-10 flex items-center justify-between flex-wrap gap-6">
            <div className="flex items-center gap-6">
              <Avatar
                src={patientData.avatar}
                alt={patientData.name}
                size="xl"
                variant="rounded"
                className="rounded-lg shadow-lg shadow-blue-gray-500/40"
              />
              <div>
                <Typography variant="h5" color="blue-gray" className="mb-1">
                  {patientData.name}
                </Typography>
                <Typography variant="small" className="font-normal text-blue-gray-600">
                  {patientData.age} • {patientData.gender} • Blood Type: {patientData.bloodType}
                </Typography>
              </div>
            </div>
            <div className="w-96">
              <Tabs value="overview">
                <TabsHeader>
                  <Tab value="overview">
                    <HomeIcon className="-mt-1 mr-2 inline-block h-5 w-5" />
                    Overview
                  </Tab>
                  <Tab value="vaccinations">
                    <ShieldCheckIcon className="-mt-0.5 mr-2 inline-block h-5 w-5" />
                    Vaccinations
                  </Tab>
                  <Tab value="appointments">
                    <CalendarDaysIcon className="-mt-1 mr-2 inline-block h-5 w-5" />
                    Appointments
                  </Tab>
                </TabsHeader>
              </Tabs>
            </div>
          </div>

          <div className="gird-cols-1 mb-12 grid gap-12 px-4 lg:grid-cols-2 xl:grid-cols-3">
            {/* Vaccination Status */}
            <div>
              <Typography variant="h6" color="blue-gray" className="mb-3">
                Vaccination Status
              </Typography>
              <div className="flex flex-col gap-12">
                {vaccinations.map((vaccination, index) => (
                  <div key={index}>
                    <Typography className="mb-4 block text-xs font-semibold uppercase text-blue-gray-500">
                      {vaccination.vaccine}
                    </Typography>
                    <div className="flex flex-col gap-6">
                      <div className="flex items-center justify-between">
                        <div>
                          <Typography className="text-sm font-normal text-blue-gray-500">
                            Due Date: {formatDate(vaccination.dueDate)}
                          </Typography>
                          <Typography className="text-sm font-normal text-blue-gray-500">
                            {vaccination.dateAdministered 
                              ? `Administered: ${formatDate(vaccination.dateAdministered)}`
                              : "Pending administration"
                            }
                          </Typography>
                        </div>
                        <Chip
                          value={vaccination.status}
                          color={getStatusColor(vaccination.status)}
                          size="sm"
                        />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            
            {/* Patient Information */}
            <div>
              <div className="mb-4 flex items-center justify-between">
                <Typography variant="h6" color="blue-gray">
                  Patient Information
                </Typography>
                <Tooltip content="Edit Patient Info">
                  <PencilIcon className="h-4 w-4 cursor-pointer text-blue-gray-500" />
                </Tooltip>
              </div>
              <Typography variant="small" className="mb-4 font-normal text-blue-gray-500">
                Medical records and contact information for {patientData.name}. Complete patient profile with emergency contacts and medical history.
              </Typography>
              
              <div className="space-y-4">
                {Object.entries({
                  "full name": patientData.name,
                  mobile: patientData.phone,
                  email: patientData.email,
                  location: patientData.address,
                  "emergency contact": patientData.emergencyContact,
                  allergies: patientData.allergies,
                  "chronic conditions": patientData.chronicConditions,
                }).map(([key, value]) => (
                  <div key={key} className="flex items-center gap-4">
                    <Typography variant="small" className="w-48 font-semibold text-blue-gray-500">
                      {key}:
                    </Typography>
                    <Typography variant="small" className="font-normal text-blue-gray-500">
                      {value}
                    </Typography>
                  </div>
                ))}
              </div>
            </div>
            
            {/* Recent Activities */}
            <div>
              <Typography variant="h6" color="blue-gray" className="mb-3">
                Recent Activities
              </Typography>
              <ul className="flex flex-col gap-6">
                {processedAppointments.length > 0 ? (
                  processedAppointments.map((props, index) => (
                    <MessageCard
                      key={index}
                      {...props}
                      action={
                        <Button variant="text" size="sm">
                          view
                        </Button>
                      }
                    />
                  ))
                ) : (
                  <Typography variant="small" className="text-blue-gray-500">
                    No recent activities
                  </Typography>
                )}
              </ul>
            </div>
          </div>
          
          <div className="px-4 pb-4">
            <Typography variant="h6" color="blue-gray" className="mb-2">
              Vaccination Records
            </Typography>
            <Typography variant="small" className="font-normal text-blue-gray-500">
              Complete vaccination history and upcoming schedules
            </Typography>
            <div className="mt-6 grid grid-cols-1 gap-12 md:grid-cols-2 xl:grid-cols-4">
              {vaccinations.map((vaccination, index) => (
                <Card key={index} color="transparent" shadow={false}>
                  <CardHeader
                    floated={false}
                    color="gray"
                    className="mx-0 mt-0 mb-4 h-64 xl:h-40 flex items-center justify-center bg-blue-50"
                  >
                    <ShieldCheckIcon className="h-16 w-16 text-blue-600" />
                  </CardHeader>
                  <CardBody className="py-0 px-1">
                    <Typography variant="small" className="font-normal text-blue-gray-500">
                      {vaccination.status === "done" ? "Completed" : "Pending"}
                    </Typography>
                    <Typography variant="h5" color="blue-gray" className="mt-1 mb-2">
                      {vaccination.vaccine}
                    </Typography>
                    <Typography variant="small" className="font-normal text-blue-gray-500">
                      Due: {formatDate(vaccination.dueDate)}
                    </Typography>
                  </CardBody>
                  <CardFooter className="mt-6 flex items-center justify-between py-0 px-1">
                    <Button variant="outlined" size="sm">
                      {vaccination.status === "done" ? "view record" : "schedule"}
                    </Button>
                    <div className="flex items-center">
                      <Chip
                        value={vaccination.status}
                        color={getStatusColor(vaccination.status)}
                        size="sm"
                      />
                    </div>
                  </CardFooter>
                </Card>
              ))}
            </div>
          </div>
        </CardBody>
      </Card>
    </>
  );
}

export default PatientDetail;     i need to add a new component as create and update and delete vaccinations