import React from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { 
  Mail, Phone, MapPin, Calendar, Edit, User,
  Star, TrendingUp, XCircle, CheckCircle, Home, UserX
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { format } from "date-fns";

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

const renderStars = (rating) => {
  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-slate-300" />);
    }
  }
  return stars;
};

const getReliabilityColor = (score) => {
  if (score >= 90) return { bg: 'bg-green-500', text: 'text-green-700', bgLight: 'bg-green-50' };
  if (score >= 70) return { bg: 'bg-yellow-500', text: 'text-yellow-700', bgLight: 'bg-yellow-50' };
  if (score >= 50) return { bg: 'bg-orange-500', text: 'text-orange-700', bgLight: 'bg-orange-50' };
  return { bg: 'bg-red-500', text: 'text-red-700', bgLight: 'bg-red-50' };
};

const calculateReliability = (staff) => {
  const coverageScore = staff.shift_coverage_percentage || 0;
  const cancellationPenalty = (staff.cancellation_count || 0) * 5;
  const ratingBonus = ((staff.rating || 0) / 5) * 20;
  
  let reliability = coverageScore + ratingBonus - cancellationPenalty;
  reliability = Math.max(0, Math.min(100, reliability));
  
  return Math.round(reliability);
};

export default function EmployeeCard({ staff }) {
  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 || calculateReliability(staff);
  const reliabilityColors = getReliabilityColor(reliabilityScore);

  return (
    <Card className="bg-white border-slate-200 shadow-lg hover:shadow-xl transition-all">
      <CardContent className="p-6 space-y-4">
        {/* Header: Name + Position + Edit */}
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            <div className="w-14 h-14 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center text-white font-bold text-xl shadow-md">
              {staff.initial || getInitials(staff.employee_name)}
            </div>
            <div>
              <h3 className="text-lg font-bold text-slate-900">
                {staff.employee_name}
              </h3>
              <p className="text-[#0A39DF] font-semibold text-sm">{staff.position || 'Staff'}</p>
            </div>
          </div>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => navigate(createPageUrl(`EditStaff?id=${staff.id}`))}
            className="hover:bg-slate-100"
          >
            <Edit className="w-4 h-4 text-slate-400" />
          </Button>
        </div>

        {/* Rating */}
        <div className="flex items-center gap-2">
          {renderStars(rating)}
          <span className="text-sm font-semibold text-slate-600 ml-1">({rating.toFixed(1)})</span>
        </div>

        {/* Reliability Bar */}
        <div className={`p-3 rounded-lg ${reliabilityColors.bgLight}`}>
          <div className="flex items-center justify-between mb-2">
            <span className={`text-xs font-semibold ${reliabilityColors.text}`}>Reliability Score</span>
            <span className={`text-lg font-bold ${reliabilityColors.text}`}>{reliabilityScore}%</span>
          </div>
          <div className="w-full bg-slate-200 rounded-full h-2 overflow-hidden">
            <div 
              className={`h-full ${reliabilityColors.bg} transition-all duration-500`}
              style={{ width: `${reliabilityScore}%` }}
            />
          </div>
        </div>

        {/* Metrics Grid: Coverage, Cancellations, No Shows */}
        <div className="grid grid-cols-3 gap-2">
          <div className={`p-3 rounded-lg text-center ${
            coveragePercentage >= 90 ? 'bg-green-50' : 
            coveragePercentage >= 70 ? 'bg-yellow-50' : 
            'bg-red-50'
          }`}>
            <TrendingUp className={`w-4 h-4 mx-auto mb-1 ${
              coveragePercentage >= 90 ? 'text-green-600' : 
              coveragePercentage >= 70 ? 'text-yellow-600' : 
              'text-red-600'
            }`} />
            <div className={`text-2xl font-bold ${
              coveragePercentage >= 90 ? 'text-green-700' : 
              coveragePercentage >= 70 ? 'text-yellow-700' : 
              'text-red-700'
            }`}>
              {coveragePercentage}%
            </div>
            <p className="text-xs text-slate-600 mt-1">Coverage</p>
          </div>

          <div className={`p-3 rounded-lg text-center ${
            cancellationCount === 0 ? 'bg-green-50' : 
            cancellationCount <= 2 ? 'bg-yellow-50' : 
            'bg-red-50'
          }`}>
            <XCircle className={`w-4 h-4 mx-auto mb-1 ${
              cancellationCount === 0 ? 'text-green-600' : 
              cancellationCount <= 2 ? 'text-yellow-600' : 
              'text-red-600'
            }`} />
            <div className={`text-2xl font-bold ${
              cancellationCount === 0 ? 'text-green-700' : 
              cancellationCount <= 2 ? 'text-yellow-700' : 
              'text-red-700'
            }`}>
              {cancellationCount}
            </div>
            <p className="text-xs text-slate-600 mt-1">Cancels</p>
          </div>

          <div className={`p-3 rounded-lg text-center ${
            noShowCount === 0 ? 'bg-green-50' : 
            noShowCount <= 1 ? 'bg-yellow-50' : 
            'bg-red-50'
          }`}>
            <UserX className={`w-4 h-4 mx-auto mb-1 ${
              noShowCount === 0 ? 'text-green-600' : 
              noShowCount <= 1 ? 'text-yellow-600' : 
              'text-red-600'
            }`} />
            <div className={`text-2xl font-bold ${
              noShowCount === 0 ? 'text-green-700' : 
              noShowCount <= 1 ? 'text-yellow-700' : 
              'text-red-700'
            }`}>
              {noShowCount}
            </div>
            <p className="text-xs text-slate-600 mt-1">No Shows</p>
          </div>
        </div>

        {/* Position Badges (removed "Skills" label) */}
        {(staff.position || staff.position_2) && (
          <div className="flex flex-wrap gap-2">
            {staff.position && (
              <Badge className="bg-[#0A39DF] text-white font-medium">
                {staff.position}
              </Badge>
            )}
            {staff.position_2 && (
              <Badge className="bg-slate-100 text-slate-700 border-slate-300 font-medium">
                {staff.position_2}
              </Badge>
            )}
          </div>
        )}

        {/* English Level & Profile Type */}
        <div className="flex flex-wrap gap-2">
          {staff.profile_type && (
            <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-300 font-medium">
              {staff.profile_type}
            </Badge>
          )}
          {staff.english && (
            <Badge variant="outline" className={`border-2 ${
              staff.english === 'Fluent' ? 'bg-green-50 text-green-700 border-green-300' :
              staff.english === 'None' ? 'bg-slate-50 text-slate-600 border-slate-300' :
              'bg-blue-50 text-blue-700 border-blue-300'
            }`}>
              {staff.english}
            </Badge>
          )}
          {staff.invoiced && (
            <Badge className="bg-emerald-500 text-white">
              <CheckCircle className="w-3 h-3 mr-1" />
              Invoiced
            </Badge>
          )}
        </div>

        {/* Contact Information */}
        <div className="space-y-2 pt-2 border-t border-slate-200">
          {staff.manager && (
            <div className="flex items-center gap-2 text-sm text-slate-700">
              <User className="w-4 h-4 text-[#0A39DF]" />
              <span className="font-semibold">Manager:</span>
              <span>{staff.manager}</span>
            </div>
          )}

          {staff.contact_number && (
            <div className="flex items-center gap-2 text-sm text-slate-700">
              <Phone className="w-4 h-4 text-[#0A39DF]" />
              <span>{staff.contact_number}</span>
            </div>
          )}

          {staff.email && (
            <div className="flex items-center gap-2 text-sm text-slate-700">
              <Mail className="w-4 h-4 text-[#0A39DF]" />
              <span className="truncate">{staff.email}</span>
            </div>
          )}

          {staff.address && (
            <div className="flex items-start gap-2 text-sm text-slate-700">
              <Home className="w-4 h-4 text-[#0A39DF] mt-0.5" />
              <span>{staff.address}</span>
            </div>
          )}

          {staff.city && !staff.address && (
            <div className="flex items-center gap-2 text-sm text-slate-700">
              <Home className="w-4 h-4 text-[#0A39DF]" />
              <span>{staff.city}</span>
            </div>
          )}

          {staff.hub_location && (
            <div className="flex items-center gap-2 text-sm text-slate-700">
              <MapPin className="w-4 h-4 text-[#0A39DF]" />
              <span>{staff.hub_location}</span>
            </div>
          )}

          {staff.check_in && (
            <div className="flex items-center gap-2 text-sm text-slate-700">
              <Calendar className="w-4 h-4 text-[#0A39DF]" />
              <span className="font-semibold">Last Check-in:</span>
              <span>{format(new Date(staff.check_in), "MMM d, yyyy")}</span>
            </div>
          )}
        </div>

        {/* Schedule */}
        {staff.schedule_days && (
          <div className="pt-2 border-t border-slate-200">
            <p className="text-xs font-semibold text-slate-500 mb-1">Schedule</p>
            <p className="text-sm text-slate-900 font-medium">{staff.schedule_days}</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}