import React, { useState, useMemo } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Users, Calendar, Clock, TrendingUp, TrendingDown, AlertCircle, CheckCircle, XCircle, Search, Filter, List, LayoutGrid, ChevronLeft, ChevronRight } from "lucide-react";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { format } from "date-fns";

export default function StaffAvailability() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");
  const [filterUtilization, setFilterUtilization] = useState("all");
  const [viewMode, setViewMode] = useState("cards");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(50);
  const [sortBy, setSortBy] = useState("need_work_index");

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

  const { data: availabilityData = [] } = useQuery({
    queryKey: ['worker-availability'],
    queryFn: () => base44.entities.WorkerAvailability.list(),
    initialData: [],
  });

  const { data: events = [] } = useQuery({
    queryKey: ['events-for-availability'],
    queryFn: () => base44.entities.Event.list(),
    initialData: [],
  });

  // Calculate metrics
  const metrics = useMemo(() => {
    const needsWork = availabilityData.filter(w => w.need_work_index >= 60).length;
    const fullyBooked = availabilityData.filter(w => w.utilization_percentage >= 90).length;
    const hasUtilization = availabilityData.filter(w => w.utilization_percentage > 0 && w.utilization_percentage < 90).length;
    const onTimeOff = availabilityData.filter(w => w.availability_status === 'BLOCKED').length;
    
    return { needsWork, fullyBooked, hasUtilization, onTimeOff };
  }, [availabilityData]);

  // Filter and search logic
  const filteredAvailability = useMemo(() => {
    let filtered = availabilityData;

    // Search
    if (searchTerm) {
      filtered = filtered.filter(a => 
        a.staff_name?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // Status filter
    if (filterStatus !== "all") {
      filtered = filtered.filter(a => a.availability_status === filterStatus);
    }

    // Utilization filter
    if (filterUtilization === "underutilized") {
      filtered = filtered.filter(a => a.utilization_percentage < 50);
    } else if (filterUtilization === "optimal") {
      filtered = filtered.filter(a => a.utilization_percentage >= 50 && a.utilization_percentage < 100);
    } else if (filterUtilization === "full") {
      filtered = filtered.filter(a => a.utilization_percentage >= 100);
    }

    // Sort
    if (sortBy === "need_work_index") {
      filtered.sort((a, b) => (b.need_work_index || 0) - (a.need_work_index || 0));
    } else if (sortBy === "utilization") {
      filtered.sort((a, b) => (a.utilization_percentage || 0) - (b.utilization_percentage || 0));
    } else if (sortBy === "name") {
      filtered.sort((a, b) => (a.staff_name || "").localeCompare(b.staff_name || ""));
    } else if (sortBy === "availability_score") {
      filtered.sort((a, b) => (b.predicted_availability_score || 0) - (a.predicted_availability_score || 0));
    }

    return filtered;
  }, [availabilityData, searchTerm, filterStatus, filterUtilization, sortBy]);

  // Pagination
  const totalPages = Math.ceil(filteredAvailability.length / itemsPerPage);
  const paginatedData = filteredAvailability.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  React.useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm, filterStatus, filterUtilization, sortBy]);

  const getUtilizationColor = (percentage) => {
    if (percentage === 0) return "text-slate-400";
    if (percentage < 50) return "text-red-600";
    if (percentage < 80) return "text-amber-600";
    return "text-green-600";
  };

  const getStatusBadge = (worker) => {
    const statusConfig = {
      'CONFIRMED_AVAILABLE': { bg: 'bg-green-100', text: 'text-green-800', label: 'Available' },
      'UNKNOWN': { bg: 'bg-gray-100', text: 'text-gray-800', label: 'Unknown' },
      'BLOCKED': { bg: 'bg-red-100', text: 'text-red-800', label: 'Unavailable' },
    };
    const config = statusConfig[worker.availability_status] || statusConfig['UNKNOWN'];
    return <Badge className={`${config.bg} ${config.text} text-[10px]`}>{config.label}</Badge>;
  };

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-[1800px] mx-auto space-y-6">
        
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">Staff Availability</h1>
            <p className="text-sm text-slate-500 mt-1">
              Showing {filteredAvailability.length} of {availabilityData.length} workers
            </p>
          </div>
          <div className="flex items-center gap-1 bg-gradient-to-r from-blue-50 to-indigo-50 p-2 rounded-xl border-2 border-blue-200">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setViewMode("cards")}
              className={viewMode === "cards" ? "bg-white text-slate-900 shadow-sm hover:bg-white" : "text-slate-600 hover:bg-white/50"}
            >
              <LayoutGrid className="w-4 h-4 mr-2" />
              Grid
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setViewMode("table")}
              className={viewMode === "table" ? "bg-[#0A39DF] text-white hover:bg-blue-700 shadow-lg" : "text-slate-600 hover:bg-white/50"}
            >
              <List className="w-4 h-4 mr-2" />
              List
            </Button>
          </div>
        </div>

        {/* Metrics Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card className="border border-slate-200 bg-slate-50/50 hover:shadow-md transition-all">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-xs mb-2 font-semibold uppercase tracking-wide">Needs Work</p>
                  <p className="text-3xl font-bold text-slate-900 mb-0.5">{metrics.needsWork}</p>
                  <p className="text-slate-500 text-xs">Available workers</p>
                </div>
                <div className="w-12 h-12 bg-white border border-slate-200 shadow-sm rounded-xl flex items-center justify-center">
                  <TrendingDown className="w-6 h-6 text-slate-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border border-green-200 bg-green-50 hover:shadow-md transition-all">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-xs mb-2 font-semibold uppercase tracking-wide">Fully Booked</p>
                  <p className="text-3xl font-bold text-slate-900 mb-0.5">{metrics.fullyBooked}</p>
                  <p className="text-slate-500 text-xs">At capacity</p>
                </div>
                <div className="w-12 h-12 bg-white border border-green-200 shadow-sm rounded-xl flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border border-teal-200 bg-teal-50 hover:shadow-md transition-all">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-xs mb-2 font-semibold uppercase tracking-wide">Active</p>
                  <p className="text-3xl font-bold text-slate-900 mb-0.5">{metrics.hasUtilization}</p>
                  <p className="text-slate-500 text-xs">Working now</p>
                </div>
                <div className="w-12 h-12 bg-white border border-teal-200 shadow-sm rounded-xl flex items-center justify-center">
                  <TrendingUp className="w-6 h-6 text-teal-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border border-blue-200 bg-blue-50 hover:shadow-md transition-all">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-slate-600 text-xs mb-2 font-semibold uppercase tracking-wide">On Time Off</p>
                  <p className="text-3xl font-bold text-slate-900 mb-0.5">{metrics.onTimeOff}</p>
                  <p className="text-slate-500 text-xs">Unavailable</p>
                </div>
                <div className="w-12 h-12 bg-white border border-blue-200 shadow-sm rounded-xl flex items-center justify-center">
                  <XCircle className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Search and Filters */}
        <Card className="border border-slate-200 shadow-sm bg-white">
          <CardContent className="p-5">
            <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
              <div className="md:col-span-2 relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <Input
                  placeholder="Search by name..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 h-10 border border-slate-300 focus:border-[#0A39DF]"
                />
              </div>
              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="h-10 border border-slate-300">
                  <SelectValue placeholder="Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="CONFIRMED_AVAILABLE">Available</SelectItem>
                  <SelectItem value="UNKNOWN">Unknown</SelectItem>
                  <SelectItem value="BLOCKED">Blocked</SelectItem>
                </SelectContent>
              </Select>
              <Select value={filterUtilization} onValueChange={setFilterUtilization}>
                <SelectTrigger className="h-10 border border-slate-300">
                  <SelectValue placeholder="Utilization" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Utilization</SelectItem>
                  <SelectItem value="underutilized">&lt; 50%</SelectItem>
                  <SelectItem value="optimal">50-99%</SelectItem>
                  <SelectItem value="full">100%+</SelectItem>
                </SelectContent>
              </Select>
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="h-10 border border-slate-300">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="need_work_index">Hours Gap</SelectItem>
                  <SelectItem value="utilization">Utilization</SelectItem>
                  <SelectItem value="availability_score">Availability Score</SelectItem>
                  <SelectItem value="name">Name</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Main Content - Table or Cards View */}
        {viewMode === "table" ? (
          <Card className="border border-slate-200 shadow-sm bg-white">
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow className="bg-gradient-to-r from-slate-50 to-blue-50 border-b border-slate-200 hover:bg-gradient-to-r">
                    <TableHead className="font-bold text-slate-700 uppercase text-xs">Name</TableHead>
                    <TableHead className="font-bold text-slate-700 uppercase text-xs">Status</TableHead>
                    <TableHead className="text-center font-bold text-slate-700 uppercase text-xs">Hours</TableHead>
                    <TableHead className="text-center font-bold text-slate-700 uppercase text-xs">Utilization</TableHead>
                    <TableHead className="text-center font-bold text-slate-700 uppercase text-xs">Hours Gap</TableHead>
                    <TableHead className="text-center font-bold text-slate-700 uppercase text-xs">Acceptance</TableHead>
                    <TableHead className="text-center font-bold text-slate-700 uppercase text-xs">Last Shift</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {paginatedData.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8 text-slate-500">
                        No workers found
                      </TableCell>
                    </TableRow>
                  ) : (
                    paginatedData.map((worker) => (
                      <TableRow key={worker.id}>
                        <TableCell>
                          <div className="flex items-center gap-3">
                            <Avatar className="w-8 h-8">
                              <AvatarFallback className="bg-blue-100 text-blue-700 text-xs font-semibold">
                                {worker.staff_name?.charAt(0) || "?"}
                              </AvatarFallback>
                            </Avatar>
                            <span className="font-medium">{worker.staff_name}</span>
                          </div>
                        </TableCell>
                        <TableCell className="py-4">
                          {getStatusBadge(worker)}
                        </TableCell>
                        <TableCell className="text-center py-4">
                          <span className="font-bold text-slate-900">
                            {worker.scheduled_hours_this_period}h
                          </span>
                          <span className="text-slate-500"> / {worker.desired_hours_this_period}h</span>
                        </TableCell>
                        <TableCell className="text-center py-4">
                          <div className="flex flex-col items-center gap-2">
                            <span className={`font-bold text-lg ${getUtilizationColor(worker.utilization_percentage)}`}>
                              {Math.round(worker.utilization_percentage)}%
                            </span>
                            <div className="w-full max-w-[120px] h-2 bg-slate-200 rounded-full overflow-hidden">
                              <div 
                                className={`h-full ${
                                  worker.utilization_percentage < 50 ? 'bg-red-500' : 
                                  worker.utilization_percentage < 80 ? 'bg-amber-500' : 
                                  'bg-green-500'
                                }`}
                                style={{ width: `${Math.min(100, worker.utilization_percentage)}%` }}
                              />
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="text-center py-4">
                          {worker.scheduled_hours_this_period < worker.desired_hours_this_period ? (
                            <Badge className="bg-red-100 text-red-800 font-bold border border-red-200">
                              Needs {worker.desired_hours_this_period - worker.scheduled_hours_this_period}h
                            </Badge>
                          ) : (
                            <Badge className="bg-green-100 text-green-800 font-bold border border-green-200">
                              Fully booked
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-center py-4">
                          <span className="font-bold text-slate-900">{worker.acceptance_rate || 0}%</span>
                        </TableCell>
                        <TableCell className="text-center text-sm text-slate-700 font-medium py-4">
                          {worker.last_shift_date ? format(new Date(worker.last_shift_date), 'MMM d') : '-'}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {paginatedData.map((worker) => {
              const staff = allStaff.find(s => s.id === worker.staff_id);

              return (
                <Card key={worker.id} className="bg-white border border-slate-200 hover:border-blue-300 hover:shadow-lg transition-all">
                  <CardContent className="p-5">
                    <div className="flex items-start gap-3">
                      <Avatar className="w-14 h-14 bg-blue-100 shadow-md ring-2 ring-blue-200">
                        <AvatarFallback className="bg-blue-100 text-blue-700 font-bold text-lg">
                          {worker.staff_name?.charAt(0)?.toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex-1 min-w-0">
                        <p className="font-bold text-slate-900 truncate text-base">{worker.staff_name}</p>
                        <p className="text-xs text-slate-600 font-medium">{staff?.position || 'Staff'}</p>

                        <div className="flex gap-1.5 mt-3 flex-wrap">
                          {getStatusBadge(worker)}
                          {worker.scheduled_hours_this_period < worker.desired_hours_this_period && (
                            <Badge className="bg-red-100 text-red-800 font-bold border border-red-200">
                              Needs {worker.desired_hours_this_period - worker.scheduled_hours_this_period}h
                            </Badge>
                          )}
                          {worker.scheduled_hours_this_period >= worker.desired_hours_this_period && (
                            <Badge className="bg-green-100 text-green-800 font-bold border border-green-200">
                              Fully booked
                            </Badge>
                          )}
                        </div>

                        <div className="mt-4 space-y-3">
                          <div className="bg-slate-50/50 border border-slate-200 rounded-lg p-3">
                            <div className="flex items-center justify-between mb-2">
                              <span className="text-xs font-bold text-slate-700 uppercase tracking-wide">Weekly Hours</span>
                              <span className="text-sm font-bold text-slate-900">
                                {worker.scheduled_hours_this_period}h / {worker.desired_hours_this_period}h
                              </span>
                            </div>
                            <div className="w-full h-2 bg-slate-200 rounded-full overflow-hidden">
                              <div 
                                className={`h-full transition-all ${
                                  worker.utilization_percentage < 50 ? 'bg-red-500' : 
                                  worker.utilization_percentage < 80 ? 'bg-amber-500' : 
                                  'bg-green-500'
                                }`}
                                style={{ width: `${Math.min(100, worker.utilization_percentage)}%` }}
                              />
                            </div>
                          </div>

                          {worker.last_shift_date && (
                            <div className="flex items-center gap-2 text-xs text-slate-600">
                              <Clock className="w-3.5 h-3.5" />
                              <span>Last shift: {format(new Date(worker.last_shift_date), 'MMM d')}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}

        {/* Pagination */}
        <Card className="border border-slate-200 shadow-sm bg-white">
          <CardContent className="p-5">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <p className="text-sm text-slate-700 font-medium">
                  Showing {((currentPage - 1) * itemsPerPage) + 1} to {Math.min(currentPage * itemsPerPage, filteredAvailability.length)} of {filteredAvailability.length} workers
                </p>
                <Select value={itemsPerPage.toString()} onValueChange={(val) => { setItemsPerPage(parseInt(val)); setCurrentPage(1); }}>
                  <SelectTrigger className="w-24 h-9 border border-slate-300">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="25">25</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                    <SelectItem value="100">100</SelectItem>
                    <SelectItem value="250">250</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="border-slate-300 hover:bg-blue-50 disabled:opacity-50"
                >
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <span className="text-sm font-bold px-4 text-slate-900">
                  Page {currentPage} of {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="border-slate-300 hover:bg-blue-50 disabled:opacity-50"
                >
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}