import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAuth } from "@/hooks/useAuth";
import { useLocation } from "wouter";
import { Clock, AlertTriangle, CheckCircle, Search, Filter, ArrowRight } from "lucide-react";

interface FormWithTiming {
  id: string;
  formNumber: string;
  indicatorNumber: string;
  title: string;
  currentDepartment: string;
  assignedToUser: string;
  creatorName: string;
  assignedAt: string;
  createdAt: string;
  processingTimeMinutes?: number;
  status: string;
  isDelayed: boolean;
  departmentHistory: Array<{
    department: string;
    receivedAt: string;
    processedAt?: string;
    processingTimeMinutes?: number;
    assignedUser: string;
  }>;
}

interface MonitoringStats {
  totalActiveForms: number;
  delayedForms: number;
  avgProcessingTime: number;
  departmentBacklogs: Array<{
    department: string;
    count: number;
    avgDelay: number;
  }>;
}

export default function MonitoringDashboard() {
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [, setLocation] = useLocation();
  const [searchTerm, setSearchTerm] = useState("");
  const [filterDepartment, setFilterDepartment] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");

  // Fetch monitoring data
  const { data: stats } = useQuery<MonitoringStats>({
    queryKey: ["/api/monitoring/stats"],
  });

  const { data: forms = [] } = useQuery<FormWithTiming[]>({
    queryKey: ["/api/monitoring/forms", searchTerm, filterDepartment, filterStatus],
  });

  const getDepartmentName = (dept: string) => {
    const names: Record<string, string> = {
      engineering: 'مهندسی',
      planning: 'برنامه‌ریزی',
      commercial: 'بازرگانی',
      quality: 'تضمین کیفیت',
      financial: 'مالی',
      laboratory: 'آزمایشگاه',
      warehouse: 'انبار',
      admin: 'مدیریت'
    };
    return names[dept] || dept;
  };

  const getStatusColor = (status: string, isDelayed: boolean) => {
    if (isDelayed) return "destructive";
    switch (status) {
      case 'pending': return "secondary";
      case 'in_progress': return "default";
      case 'completed': return "outline";
      default: return "secondary";
    }
  };

  const formatProcessingTime = (minutes?: number) => {
    if (!minutes) return "در حال پردازش";
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    const days = Math.floor(hours / 24);
    const remainingHours = hours % 24;
    
    if (days > 0) {
      return `${days}روز ${remainingHours}س`;
    } else if (hours > 0) {
      return `${hours}س ${mins}د`;
    }
    return `${mins}د`;
  };

  const formatPersianDate = (dateStr: string) => {
    try {
      return new Intl.DateTimeFormat('fa-IR', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      }).format(new Date(dateStr));
    } catch (e) {
      return 'نامشخص';
    }
  };

  const filteredForms = forms.filter(form => {
    const matchesSearch = form.formNumber.includes(searchTerm) || 
                         form.indicatorNumber.includes(searchTerm) ||
                         form.title.includes(searchTerm) ||
                         form.assignedToUser.includes(searchTerm) ||
                         form.creatorName.includes(searchTerm);
    const matchesDepartment = filterDepartment === "all" || form.currentDepartment === filterDepartment;
    const matchesStatus = filterStatus === "all" || 
                         (filterStatus === "delayed" && form.isDelayed) ||
                         (filterStatus === "normal" && !form.isDelayed);
    
    return matchesSearch && matchesDepartment && matchesStatus;
  });

  return (
    <div className="container mx-auto p-6 space-y-6" dir="rtl">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4 space-x-reverse">
          <Button 
            onClick={() => setLocation('/')}
            variant="outline" 
            size="sm"
            className="flex items-center"
          >
            <ArrowRight className="w-4 h-4 ml-2" />
            بازگشت به صفحه اصلی
          </Button>
          <h1 className="text-3xl font-bold">داشبورد مانیتورینگ</h1>
        </div>
        <Button 
          onClick={() => {
            queryClient.invalidateQueries({ queryKey: ["/api/monitoring"] });
          }}
          variant="outline" 
          size="sm"
        >
          به‌روزرسانی
        </Button>
      </div>



      {/* Department Backlogs */}
      {stats?.departmentBacklogs && stats.departmentBacklogs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>وضعیت واحدها</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {stats.departmentBacklogs.map((dept) => (
                <div key={dept.department} className="p-3 border rounded-lg">
                  <div className="font-medium">{getDepartmentName(dept.department)}</div>
                  <div className="text-sm text-gray-600">
                    {dept.count} فرم در انتظار
                  </div>
                  {dept.avgDelay > 0 && (
                    <div className="text-sm text-red-600">
                      میانگین تاخیر: {formatProcessingTime(dept.avgDelay)}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                <Input
                  placeholder="جستجو بر اساس شماره فرم، اندیکاتور، عنوان، سازنده یا مسئول..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pr-10"
                />
              </div>
            </div>

            <Select value={filterDepartment} onValueChange={setFilterDepartment}>
              <SelectTrigger className="w-full md:w-48">
                <SelectValue placeholder="فیلتر واحد" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">همه واحدها</SelectItem>
                <SelectItem value="engineering">مهندسی</SelectItem>
                <SelectItem value="planning">برنامه‌ریزی</SelectItem>
                <SelectItem value="commercial">بازرگانی</SelectItem>
                <SelectItem value="quality">تضمین کیفیت</SelectItem>
                <SelectItem value="financial">مالی</SelectItem>
                <SelectItem value="laboratory">آزمایشگاه</SelectItem>
                <SelectItem value="warehouse">انبار</SelectItem>
              </SelectContent>
            </Select>

            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-full md:w-48">
                <SelectValue placeholder="فیلتر وضعیت" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">همه</SelectItem>
                <SelectItem value="normal">عادی</SelectItem>
                <SelectItem value="delayed">با تاخیر</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Forms Table */}
      <Card>
        <CardHeader>
          <CardTitle>فرم‌های در حال پردازش</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    شماره فرم
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    اندیکاتور
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    عنوان محصول
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    سازنده فرم
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    تاریخ ایجاد
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    واحد فعلی
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    مسئول فعلی
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    زمان در صف
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                    وضعیت
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {filteredForms.map((form) => (
                  <tr key={form.id} className={form.isDelayed ? "bg-red-50" : ""}>
                    <td className="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {form.formNumber}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-blue-600 font-medium">
                      {form.indicatorNumber}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      {form.title}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      {form.creatorName}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatPersianDate(form.createdAt)}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      <Badge variant="outline" className="text-xs">
                        {getDepartmentName(form.currentDepartment)}
                      </Badge>
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      {form.assignedToUser}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatProcessingTime(form.processingTimeMinutes)}
                    </td>
                    <td className="px-4 py-4 whitespace-nowrap">
                      <Badge variant={getStatusColor(form.status, form.isDelayed)}>
                        {form.isDelayed ? "تاخیر" : "عادی"}
                      </Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}