import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Users, ChevronRight, MapPin, Droplets, Ruler, Weight, AlertTriangle } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { usePractitionerStore } from '../store/usePractitionerStore';

function initials(name: string) {
  return name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
}

export default function PatientsPage() {
  const { patients, patientsLoading } = usePractitionerStore();
  const navigate = useNavigate();
  const [search, setSearch] = useState('');

  const filtered = useMemo(() => {
    if (!search.trim()) return patients;
    const q = search.toLowerCase();
    return patients.filter(
      p =>
        p.dispName.toLowerCase().includes(q) ||
        p.username.toLowerCase().includes(q) ||
        (p.residentCity || '').toLowerCase().includes(q),
    );
  }, [patients, search]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">My Patients</h1>
        <p className="text-sm text-muted-foreground mt-1">
          {patients.length} patient{patients.length !== 1 ? 's' : ''} sharing data with you
        </p>
      </div>

      {/* Search */}
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search patients by name or city..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>

      {/* Loading */}
      {patientsLoading && (
        <div className="flex items-center justify-center py-16">
          <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
        </div>
      )}

      {/* Empty */}
      {!patientsLoading && filtered.length === 0 && (
        <Card className="flex flex-col items-center justify-center py-16">
          <div className="h-14 w-14 rounded-full bg-muted flex items-center justify-center mb-4">
            <Users className="h-7 w-7 text-muted-foreground" />
          </div>
          <p className="text-sm font-medium">
            {search ? 'No patients match your search' : 'No patients yet'}
          </p>
          <p className="text-xs text-muted-foreground mt-1">
            {search ? 'Try a different search term' : 'Patients will appear here once they share their data with you'}
          </p>
        </Card>
      )}

      {/* Patient grid */}
      {!patientsLoading && filtered.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {filtered.map(patient => {
            const details = [patient.residentCity, patient.bloodType].filter(Boolean);
            const hasAllergies = patient.allergies && patient.allergies.length > 0;

            return (
              <Card
                key={patient._id}
                className="group cursor-pointer transition-all hover:shadow-md hover:border-primary/20"
                onClick={() => {
                  navigate(`/patients/${patient._id}`);
                }}
              >
                <CardContent className="p-5">
                  {/* Top row: avatar + name + chevron */}
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <Avatar className="h-11 w-11">
                        <AvatarFallback className="bg-primary/10 text-primary text-sm font-semibold">
                          {initials(patient.dispName)}
                        </AvatarFallback>
                      </Avatar>
                      <div className="min-w-0">
                        <p className="text-sm font-semibold truncate">{patient.dispName}</p>
                        {details.length > 0 && (
                          <div className="flex items-center gap-1.5 mt-0.5">
                            {patient.residentCity && (
                              <span className="flex items-center gap-1 text-xs text-muted-foreground">
                                <MapPin className="h-3 w-3" />
                                {patient.residentCity}
                              </span>
                            )}
                            {patient.residentCity && patient.bloodType && (
                              <span className="text-muted-foreground/40">·</span>
                            )}
                            {patient.bloodType && (
                              <span className="flex items-center gap-1 text-xs text-muted-foreground">
                                <Droplets className="h-3 w-3" />
                                {patient.bloodType}
                              </span>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                    <ChevronRight className="h-4 w-4 text-muted-foreground/40 group-hover:text-primary transition-colors mt-1 shrink-0" />
                  </div>

                  {/* Vitals + allergies */}
                  {(patient.height || patient.weight || hasAllergies) && (
                    <>
                      <Separator className="my-3" />
                      <div className="flex flex-wrap items-center gap-1.5">
                        {patient.height && (
                          <Badge variant="outline" className="gap-1 font-normal text-muted-foreground">
                            <Ruler className="h-3 w-3" />
                            {patient.height} cm
                          </Badge>
                        )}
                        {patient.weight && (
                          <Badge variant="outline" className="gap-1 font-normal text-muted-foreground">
                            <Weight className="h-3 w-3" />
                            {patient.weight} kg
                          </Badge>
                        )}
                        {hasAllergies && (
                          <Badge variant="destructive" className="gap-1">
                            <AlertTriangle className="h-3 w-3" />
                            {patient.allergies!.length} allerg{patient.allergies!.length === 1 ? 'y' : 'ies'}
                          </Badge>
                        )}
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
