import { Card, CardContent } from "@/common/components/ui/card";
import { Badge } from "@/common/components/ui/badge";
import { Button } from "@/common/components/ui/button";
import { motion } from "framer-motion";
import {
  Mail, Phone, MapPin, Calendar, Edit,
  Star, TrendingUp, XCircle, CheckCircle, UserX,
  Shield, Globe, Briefcase
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import type { Staff } from "../../type";


const getInitials = (name: string) => {
  if (!name) return "?";
  return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
};

const renderStars = (rating: number) => {
  const stars = [];
  const fullStars = Math.floor(rating || 0);

  for (let i = 0; i < 5; i++) {
    if (i < fullStars) {
      stars.push(<Star key={i} className="w-4 h-4 fill-amber-400 text-amber-400" />);
    } else {
      stars.push(<Star key={i} className="w-4 h-4 text-muted/40" />);
    }
  }
  return stars;
};

const getReliabilityColor = (score: number) => {
  if (score >= 90) return {
    bg: 'bg-emerald-500',
    text: 'text-emerald-700',
    bgLight: 'bg-emerald-50/50',
    border: 'border-emerald-200',
    icon: <Shield className="w-3 h-3" />
  };
  if (score >= 70) return {
    bg: 'bg-amber-500',
    text: 'text-amber-700',
    bgLight: 'bg-amber-50/50',
    border: 'border-amber-200',
    icon: <TrendingUp className="w-3 h-3" />
  };
  return {
    bg: 'bg-rose-500',
    text: 'text-rose-700',
    bgLight: 'bg-rose-50/50',
    border: 'border-rose-200',
    icon: <XCircle className="w-3 h-3" />
  };
};

const formatDate = (dateStr: string) => {
  try {
    if (!dateStr) return "N/A";
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  } catch (e) {
    console.error("Failed to format date", e);
    return "N/A";
  }
}

interface EmployeeCardProps {
  staff: Staff;
}

export default function EmployeeCard({ staff }: EmployeeCardProps) {
  const navigate = useNavigate();

  const coveragePercentage = staff.shift_coverage_percentage || 0;
  const cancellationCount = staff.cancellation_count || 0;
  const noShowCount = staff.no_show_count || 0;
  const rating = staff.rating || 0;
  const reliabilityScore = staff.reliability_score || 0;
  const reliability = getReliabilityColor(reliabilityScore);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      whileHover={{ y: -4 }}
      transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
      className="h-full"
    >
      <Card className="h-full backdrop-blur-sm border-border/50 transition-premium overflow-hidden group">
        <div className="absolute inset-0 bg-gradient-to-br from-primary/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />

        <CardContent className="p-6 space-y-5 relative z-10">
          {/* Top Row: Avatar & Actions */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="relative">
                <div className="w-16 h-16 bg-primary/10 rounded-xl flex items-center justify-center text-primary font-bold text-xl transform group-hover:scale-105 transition-premium border border-primary/20">
                  {staff.initial || getInitials(staff.employee_name)}
                </div>
                <div className="absolute -bottom-1 -right-1 w-6 h-6 bg-background border-2 border-border rounded-full flex items-center justify-center">
                  <div className={`w-2 h-2 rounded-full ${coveragePercentage >= 80 ? 'bg-emerald-500 animate-pulse' : 'bg-amber-500'}`} />
                </div>
              </div>
              <div>
                <h3 className="text-xl font-bold text-foreground group-hover:text-primary transition-colors">
                  {staff.employee_name}
                </h3>
                <div className="flex items-center gap-1.5 text-muted-foreground">
                  <Briefcase className="w-3.5 h-3.5 text-primary" />
                  <span className="text-sm font-medium">{staff.position || 'Professional Staff'}</span>
                </div>
              </div>
            </div>

            <Button
              variant="ghost"
              size="icon"
              onClick={() => navigate(`/staff/${staff.id}/edit`)}
              className="rounded-full hover:bg-primary/10 hover:text-primary transition-premium border border-transparent hover:border-primary/20"
            >
              <Edit className="w-4 h-4" />
            </Button>
          </div>

          {/* Reliability & Rating */}
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-1">
              {renderStars(rating)}
              <span className="text-sm font-bold text-foreground/80 ml-1">{rating.toFixed(1)}</span>
            </div>

            <div className={`flex items-center gap-1 px-3 py-1 rounded-full border ${reliability.border} ${reliability.bgLight} ${reliability.text} text-[10px] font-bold uppercase tracking-wider`}>
              {reliability.icon}
              {reliabilityScore}% Reliable
            </div>
          </div>

          {/* Stats & Professional Details */}
          <div className="space-y-1 py-1">
            {[
              { label: 'Coverage', value: `${coveragePercentage}%`, icon: <TrendingUp className="w-4 h-4" />, color: 'emerald' },
              { label: 'Cancels', value: cancellationCount, icon: <XCircle className="w-4 h-4" />, color: cancellationCount === 0 ? 'emerald' : 'rose' },
              { label: 'No Shows', value: noShowCount, icon: <UserX className="w-4 h-4" />, color: noShowCount === 0 ? 'emerald' : 'rose' },
              staff.profile_type && { label: 'Level', value: staff.profile_type, icon: <Shield className="w-4 h-4" />, color: 'primary' },
              staff.english && { label: 'English', value: staff.english, icon: <Globe className="w-4 h-4" />, color: staff.english === 'Fluent' ? 'emerald' : 'blue' },
              staff.invoiced && { label: 'Status', value: 'Verified', icon: <CheckCircle className="w-4 h-4" />, color: 'emerald' },
            ].filter(Boolean).map((item: any, i) => (
              <div key={i} className="flex items-center justify-between group/item p-1 rounded-xl hover:bg-muted/40 transition-premium border border-transparent hover:border-border/50">
                <div className="flex items-center gap-3">
                  <div className={`w-8 h-8 rounded-lg flex items-center justify-center transition-premium group-hover/item:scale-110 border border-transparent group-hover/item:border-border/50 ${item.color === 'emerald' ? 'bg-emerald-500/10 text-emerald-600' :
                    item.color === 'rose' ? 'bg-rose-500/10 text-rose-600' :
                      item.color === 'primary' ? 'bg-primary/10 text-primary' :
                        'bg-blue-500/10 text-blue-600'
                    }`}>
                    {item.icon}
                  </div>
                  <span className="text-[11px] font-bold text-muted-foreground uppercase tracking-widest">{item.label}</span>
                </div>
                <Badge
                  variant="outline"
                  className={`font-black text-[10px] h-6 px-2.5 border-transparent ${item.color === 'emerald' ? 'bg-emerald-500/10 text-emerald-700' :
                    item.color === 'rose' ? 'bg-rose-500/10 text-rose-700' :
                      item.color === 'primary' ? 'bg-primary/10 text-primary' :
                        'bg-blue-500/10 text-blue-700'
                    }`}
                >
                  {item.value}
                </Badge>
              </div>
            ))}
          </div>

          {/* Contact Details with Glass effect */}
          <div className="space-y-1 pt-4 border-t border-border/40 relative">
            {[
              { icon: <Mail className="w-4 h-4" />, text: staff.email, visible: !!staff.email },
              { icon: <Phone className="w-4 h-4" />, text: staff.contact_number, visible: !!staff.contact_number },
              { icon: <MapPin className="w-4 h-4" />, text: staff.hub_location, visible: !!staff.hub_location },
              { icon: <Calendar className="w-4 h-4" />, text: `Updated ${formatDate(staff.check_in || '')}`, visible: !!staff.check_in },
            ].filter(d => d.visible).map((detail, i) => (
              <div key={i} className="flex items-center gap-2 text-sm text-muted-foreground group/detail cursor-pointer hover:text-foreground transition-colors text-ellipsis overflow-hidden">
                <div className="w-8 h-8 shrink-0 rounded-lg bg-secondary/50 flex items-center justify-center group-hover/detail:bg-primary/10 group-hover/detail:text-primary transition-premium text-ellipsis">
                  {detail.icon}
                </div>
                <span className="truncate flex-1 font-medium">{detail.text}</span>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}
