import React from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Users, Star, Calendar, Plus } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";

export default function VendorStaff() {
  const navigate = useNavigate();

  const { data: user } = useQuery({
    queryKey: ['current-user'],
    queryFn: () => base44.auth.me(),
  });

  const { data: staff } = useQuery({
    queryKey: ['vendor-staff'],
    queryFn: () => base44.entities.Staff.list(),
    initialData: [],
  });

  // Filter staff to only show THIS vendor's staff
  const myStaff = staff.filter(s => 
    s.vendor_id === user?.id || 
    s.vendor_name === user?.company_name ||
    s.created_by === user?.email
  );

  const stats = {
    total: myStaff.length,
    active: myStaff.filter(s => s.action !== 'Inactive').length,
    topRated: myStaff.filter(s => s.rating >= 4.5).length,
    avgRating: myStaff.length > 0 
      ? (myStaff.reduce((sum, s) => sum + (s.rating || 0), 0) / myStaff.length).toFixed(1)
      : "0.0",
  };

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold text-[#1C323E]">My Staff</h1>
            <p className="text-slate-500 mt-1">Manage your workforce</p>
          </div>
          <Button 
            onClick={() => navigate(createPageUrl("AddStaff"))}
            className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
          >
            <Plus className="w-4 h-4 mr-2" />
            Add Staff
          </Button>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <Card className="border-slate-200">
            <CardContent className="p-6">
              <Users className="w-8 h-8 text-[#0A39DF] mb-2" />
              <p className="text-sm text-slate-500">Total Staff</p>
              <p className="text-3xl font-bold text-[#1C323E]">{stats.total}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <Calendar className="w-8 h-8 text-green-600 mb-2" />
              <p className="text-sm text-slate-500">Active</p>
              <p className="text-3xl font-bold text-green-600">{stats.active}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <Star className="w-8 h-8 text-amber-600 mb-2" />
              <p className="text-sm text-slate-500">Top Rated</p>
              <p className="text-3xl font-bold text-amber-600">{stats.topRated}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <Star className="w-8 h-8 text-blue-600 mb-2" />
              <p className="text-sm text-slate-500">Avg Rating</p>
              <p className="text-3xl font-bold text-blue-600">{stats.avgRating}</p>
            </CardContent>
          </Card>
        </div>

        {/* Staff Grid */}
        {myStaff.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {myStaff.map((member) => (
              <Card key={member.id} className="border-slate-200 hover:shadow-lg transition-shadow">
                <CardContent className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="w-12 h-12 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-full flex items-center justify-center text-white font-bold text-lg">
                      {member.employee_name?.charAt(0) || '?'}
                    </div>
                    {member.rating && (
                      <Badge className="bg-amber-100 text-amber-700">
                        <Star className="w-3 h-3 mr-1" />
                        {member.rating}
                      </Badge>
                    )}
                  </div>
                  <h3 className="font-bold text-lg text-[#1C323E] mb-1">{member.employee_name}</h3>
                  <p className="text-sm text-slate-500 mb-3">{member.position || 'Staff Member'}</p>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between">
                      <span className="text-slate-600">Shifts:</span>
                      <span className="font-semibold">{member.total_shifts || 0}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-600">Coverage:</span>
                      <span className="font-semibold text-green-600">{member.shift_coverage_percentage || 0}%</span>
                    </div>
                  </div>
                  <Button
                    onClick={() => navigate(createPageUrl("EditStaff") + `?id=${member.id}`)}
                    variant="outline"
                    className="w-full mt-4 hover:bg-[#0A39DF] hover:text-white"
                  >
                    View Profile
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <Card className="border-slate-200">
            <CardContent className="p-12 text-center">
              <Users className="w-16 h-16 mx-auto text-slate-300 mb-4" />
              <h3 className="text-xl font-semibold text-slate-700 mb-2">No Staff Members Yet</h3>
              <p className="text-slate-500 mb-6">Start building your team by adding staff members</p>
              <Button 
                onClick={() => navigate(createPageUrl("AddStaff"))}
                className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
              >
                <Plus className="w-4 h-4 mr-2" />
                Add First Staff Member
              </Button>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}