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, Search, Filter, Eye, ArrowLeft, X } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import ProgressIndicator from "@/components/ProgressIndicator";
import EngineeringForm from "@/components/EngineeringForm";
import PlanningForm from "@/components/PlanningForm";
import CommercialForm from "@/components/CommercialForm";
import QualityForm from "@/components/QualityForm";
import FinancialForm from "@/components/FinancialForm";
import LaboratoryForm from "@/components/LaboratoryForm";
import WarehouseForm from "@/components/WarehouseForm";

interface PendingForm {
  id: string;
  formNumber: string;
  indicatorNumber: string;
  productName: string;
  currentDepartment: string;
  assignedToUser: string;
  creatorName: string;
  createdAt: string;
  lastTransitionDate: string;
  delayDays: number;
  status: string;
  isOverdue: boolean;
}

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

  // Fetch pending forms data
  const { data: pendingForms = [], isLoading, refetch } = useQuery<PendingForm[]>({
    queryKey: ["/api/pending-forms", searchTerm || "undefined", filterDepartment || "all"],
  });

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

  const getDelayColor = (days: number) => {
    if (days >= 7) return "destructive"; // بیش از یک هفته
    if (days >= 3) return "default"; // بیش از 3 روز
    return "secondary"; // زیر 3 روز
  };

  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 handleRefresh = () => {
    refetch();
    queryClient.invalidateQueries({ queryKey: ["/api/pending-forms"] });
  };

  const FormDetailsModal = ({ form }: { form: PendingForm }) => {
    const [open, setOpen] = useState(false);
    
    const { data: fullForm, isLoading: isFormLoading } = useQuery({
      queryKey: ["/api/forms", form.id, "view"],
      queryFn: () => fetch(`/api/forms/${form.id}/view`).then(res => {
        if (!res.ok) throw new Error('Failed to fetch form');
        return res.json();
      }),
      enabled: open
    });

    return (
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
          <Button
            size="sm"
            variant="ghost"
            className="text-blue-600 hover:text-blue-800"
          >
            <Eye className="h-4 w-4 mr-1" />
            مشاهده
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>مشاهده فرم {form.indicatorNumber}</DialogTitle>
          </DialogHeader>
          {isFormLoading ? (
            <div className="flex justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
          ) : fullForm ? (
            <div className="space-y-6">
              {/* Progress Indicator */}
              <ProgressIndicator 
                departments={[
                  'engineering',
                  'planning', 
                  'commercial',
                  'quality',
                  'financial',
                  'laboratory',
                  'warehouse',
                  'admin'
                ]}
                departmentNames={{
                  'engineering': 'مهندسی',
                  'planning': 'برنامه‌ریزی',
                  'commercial': 'بازرگانی', 
                  'quality': 'کیفیت',
                  'financial': 'مالی',
                  'laboratory': 'آزمایشگاه',
                  'warehouse': 'انبار',
                  'admin': 'مدیریت'
                }}
                currentDepartment={fullForm.currentDepartment}
                completedDepartments={[]}
              />

              {/* Form Header */}
              <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-lg border">
                <div className="grid grid-cols-2 gap-6">
                  <div>
                    <h2 className="text-xl font-bold text-gray-900 mb-2">
                      فرم درخواست نمونه محصول جدید
                    </h2>
                    <div className="space-y-1 text-sm text-gray-600">
                      <p><span className="font-medium">شماره فرم:</span> {fullForm.formNumber}</p>
                      <p><span className="font-medium">شماره اندیکاتور:</span> {fullForm.indicatorNumber}</p>
                    </div>
                  </div>
                  <div className="space-y-1 text-sm text-gray-600">
                    <p><span className="font-medium">نام محصول:</span> {fullForm.productName}</p>
                    <p><span className="font-medium">تاریخ ایجاد:</span> {formatPersianDate(fullForm.createdAt)}</p>
                    <p><span className="font-medium">وضعیت:</span> 
                      <Badge variant="outline" className="mr-2">
                        {getDepartmentName(fullForm.currentDepartment)}
                      </Badge>
                    </p>
                  </div>
                </div>
              </div>

              {/* Department Forms - Read Only */}
              <div className="space-y-6">
                {/* Engineering Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-blue-700">واحد مهندسی</h3>
                  <EngineeringForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>

                {/* Planning Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-green-700">واحد برنامه‌ریزی</h3>
                  <PlanningForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>

                {/* Commercial Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-purple-700">واحد بازرگانی</h3>
                  <CommercialForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>

                {/* Quality Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-red-700">واحد کیفیت</h3>
                  <QualityForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>

                {/* Financial Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-orange-700">واحد مالی</h3>
                  <FinancialForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>

                {/* Laboratory Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-indigo-700">واحد آزمایشگاه</h3>
                  <LaboratoryForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>

                {/* Warehouse Form */}
                <div className="border rounded-lg p-4">
                  <h3 className="text-lg font-semibold mb-4 text-teal-700">واحد انبار</h3>
                  <WarehouseForm 
                    form={fullForm} 
                    onChange={() => {}} 
                    readOnly={true}
                  />
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              خطا در بارگذاری اطلاعات فرم
            </div>
          )}
        </DialogContent>
      </Dialog>
    );
  };

  if (isLoading) {
    return (
      <div className="container mx-auto p-6">
        <div className="text-center py-8">در حال بارگیری...</div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-7xl">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={() => setLocation("/")}
            className="text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            بازگشت
          </Button>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <Clock className="h-6 w-6" />
            فرم‌های در حال انتظار
          </h1>
        </div>
        <Button onClick={handleRefresh} variant="outline">
          به‌روزرسانی
        </Button>
      </div>

      {/* Filters */}
      <Card className="mb-6">
        <CardContent className="p-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute right-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="جستجو در شماره اندیکاتور، نام محصول یا سازنده..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pr-10"
                />
              </div>
            </div>
            <div className="w-full md:w-48">
              <Select value={filterDepartment} onValueChange={setFilterDepartment}>
                <SelectTrigger>
                  <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>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Summary Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">کل فرم‌های در انتظار</p>
                <p className="text-2xl font-bold">{pendingForms.length}</p>
              </div>
              <Clock className="h-8 w-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">فرم‌های با تاخیر (+7 روز)</p>
                <p className="text-2xl font-bold text-red-600">
                  {pendingForms.filter(f => f.delayDays >= 7).length}
                </p>
              </div>
              <AlertTriangle className="h-8 w-8 text-red-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Forms Table */}
      <Card>
        <CardHeader>
          <CardTitle>لیست فرم‌های در حال انتظار</CardTitle>
        </CardHeader>
        <CardContent>
          {pendingForms.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              هیچ فرم در حال انتظاری یافت نشد
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b">
                    <th className="text-right py-3 px-4 font-medium text-gray-700">شماره اندیکاتور</th>
                    <th className="text-right py-3 px-4 font-medium text-gray-700">نام محصول</th>
                    <th className="text-right py-3 px-4 font-medium text-gray-700">تاریخ ایجاد</th>
                    <th className="text-right py-3 px-4 font-medium text-gray-700">واحد فعلی</th>
                    <th className="text-right py-3 px-4 font-medium text-gray-700">زمان تاخیر</th>
                    <th className="text-center py-3 px-4 font-medium text-gray-700">عملیات</th>
                  </tr>
                </thead>
                <tbody>
                  {pendingForms.map((form) => (
                    <tr key={form.id} className="border-b hover:bg-gray-50">
                      <td className="py-4 px-4">
                        <div className="font-medium text-blue-600">
                          {form.indicatorNumber}
                        </div>
                        <div className="text-xs text-gray-500">
                          {form.formNumber}
                        </div>
                      </td>
                      <td className="py-4 px-4">
                        <div className="font-medium">{form.productName}</div>
                      </td>
                      <td className="py-4 px-4 text-sm text-gray-500">
                        {formatPersianDate(form.createdAt)}
                      </td>
                      <td className="py-4 px-4">
                        <Badge variant="outline" className="text-xs">
                          {getDepartmentName(form.currentDepartment)}
                        </Badge>
                      </td>
                      <td className="py-4 px-4">
                        <Badge variant={getDelayColor(form.delayDays)} className="text-xs">
                          {form.delayDays} روز
                          {form.delayDays >= 7 && (
                            <AlertTriangle className="h-3 w-3 mr-1" />
                          )}
                        </Badge>
                      </td>
                      <td className="py-4 px-4 text-center">
                        <FormDetailsModal form={form} />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}