import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { apiRequest, queryClient, isUnauthorizedError } from "@/lib/queryClient";
import { useLocation } from "wouter";
import {
  ClipboardList,
  Clock,
  CheckCircle,
  AlertTriangle,
  Plus,
  Users,
  LogOut,
  Archive,
  Building,
  Trash2
} from "lucide-react";

interface Form {
  id: string;
  formNumber: string;
  indicatorNumber?: string;
  currentDepartment: string;
  status: string;
  createdAt: string;
  productType?: string;
  delegatorName?: string;
}

interface DashboardStats {
  totalForms: number;
  pendingForms: number;
  completedForms: number;
  inProgressForms: number;
}

export default function Home() {
  const { user, isLoading: authLoading } = useAuth();
  const [, setLocation] = useLocation();
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Redirect to login if not authenticated
  useEffect(() => {
    if (!authLoading && !user) {
      toast({
        title: "غیرمجاز",
        description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
        variant: "destructive",
      });
      setTimeout(() => {
        window.location.href = "/api/login";
      }, 500);
      return;
    }
  }, [user, authLoading, toast]);

  // Fetch dashboard stats
  const { data: stats, isLoading: statsLoading } = useQuery<DashboardStats>({
    queryKey: ["/api/dashboard/stats"],
    retry: false,
  });

  // Fetch forms
  const { data: forms = [], isLoading: formsLoading } = useQuery<Form[]>({
    queryKey: ["/api/forms"],
    retry: false,
  });

  // Create new form mutation
  const createFormMutation = useMutation({
    mutationFn: async () => {
      console.log("Creating new form...");
      const response = await apiRequest("POST", "/api/forms", {
        productName: "فرم جدید",
        indicatorNumber: `IND-${Date.now().toString().slice(-6)}`,
        currentDepartment: "engineering",
        partsTable: []
      });
      return response.json();
    },
    onSuccess: (form) => {
      console.log("Form created successfully:", form);
      toast({
        title: "موفقیت",
        description: "فرم جدید با موفقیت ایجاد شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
      setLocation(`/form/${form.id}`);
    },
    onError: (error) => {
      console.error("Form creation error:", error);
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: "خطا در ایجاد فرم جدید",
        variant: "destructive",
      });
    },
  });

  // Logout mutation
  const logoutMutation = useMutation({
    mutationFn: async () => {
      console.log("Sending logout request");
      try {
        const response = await fetch("/api/auth/logout", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
        });
        
        if (!response.ok) {
          console.warn("Logout response not ok, but proceeding with client cleanup");
        }
        
        return response.json().catch(() => ({ message: "Logged out" }));
      } catch (error) {
        console.warn("Logout request failed, but proceeding with client cleanup:", error);
        return { message: "Logged out" };
      }
    },
    onSuccess: (data) => {
      console.log("Logout successful:", data);
      toast({
        title: "موفقیت",
        description: "با موفقیت خارج شدید",
      });
      
      // Clear all cached data and redirect immediately
      queryClient.clear();
      setLocation("/login");
    },
    onError: (error) => {
      console.error("Logout error:", error);
      // Even on error, clear local data and redirect
      queryClient.clear();
      setLocation("/login");
    },
  });

  // Delete form mutation
  const deleteFormMutation = useMutation({
    mutationFn: (formId: string) => apiRequest("DELETE", `/api/forms/${formId}`, {}),
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "فرم با موفقیت حذف شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
    },
    onError: (error: any) => {
      toast({
        title: "خطا",
        description: error.message || "خطا در حذف فرم",
        variant: "destructive",
      });
    },
  });

  const handleLogout = () => {
    logoutMutation.mutate();
  };

  const handleCreateForm = () => {
    createFormMutation.mutate();
  };

  const handleFormClick = (formId: string) => {
    setLocation(`/form/${formId}`);
  };

  const handleDeleteForm = (formId: string) => {
    if (confirm("آیا از حذف این فرم اطمینان دارید؟")) {
      deleteFormMutation.mutate(formId);
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return <Badge className="status-pending">در انتظار</Badge>;
      case 'completed':
        return <Badge className="status-completed">تکمیل شده</Badge>;
      case 'in_progress':
        return <Badge className="status-in-progress">در حال بررسی</Badge>;
      default:
        return <Badge variant="secondary">{status}</Badge>;
    }
  };

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

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p>در حال بارگذاری...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return null;
  }

  return (
    <div className="min-h-screen bg-background page-transition">
      {/* Header - Flatly Theme */}
      <header className="bg-primary shadow-sm border-b-0">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center">
              <div className="w-10 h-10 bg-primary-foreground/20 rounded-lg flex items-center justify-center ml-3">
                <ClipboardList className="text-primary-foreground w-5 h-5" />
              </div>
              <div>
                <h1 className="text-lg font-semibold text-primary-foreground">
                  سیستم تامین نمونه کالای جدید
                </h1>
                <p className="text-sm text-primary-foreground/80">
                  کاربر: {user.fullName} - {getDepartmentName(user.department)}
                </p>
              </div>
            </div>
            
            <div className="flex items-center space-x-4 space-x-reverse">
              {user.department === 'admin' && (
                <Button
                  variant="secondary"
                  onClick={() => setLocation('/admin')}
                  className="text-sm bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0"
                >
                  <Users className="w-4 h-4 ml-2" />
                  مدیریت کاربران
                </Button>
              )}
              <Button
                variant="outline"
                onClick={() => setLocation('/pending')}
                className="text-sm bg-primary-foreground/10 hover:bg-primary-foreground/20 text-primary-foreground border-primary-foreground/30"
              >
                <Clock className="w-4 h-4 ml-2" />
                فرم‌های در حال انتظار
              </Button>
              <Button
                variant="outline"
                onClick={() => setLocation('/archived')}
                className="text-sm bg-primary-foreground/10 hover:bg-primary-foreground/20 text-primary-foreground border-primary-foreground/30"
              >
                <Archive className="w-4 h-4 ml-2" />
                آرشیو فرم‌ها
              </Button>
              <Button
                variant="ghost"
                onClick={handleLogout}
                disabled={logoutMutation.isPending}
                className="text-primary-foreground/80 hover:text-primary-foreground hover:bg-primary-foreground/10"
              >
                <LogOut className="w-4 h-4 ml-2" />
                خروج
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Card className="border-border shadow-lg">
          <CardContent className="p-6">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold text-foreground">داشبورد واحد</h2>
              {user.department === 'engineering' && (
                <Button
                  onClick={handleCreateForm}
                  disabled={createFormMutation.isPending}
                  className="text-sm minty-success border-0 hover:opacity-90 transition-opacity px-4 py-2 rounded-md font-medium"
                >
                  <Plus className="w-4 h-4 ml-2" />
                  ایجاد فرم جدید
                </Button>
              )}
            </div>
            
            {/* Statistics Cards - Flatly Theme */}
            {!statsLoading && stats && (
              <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div className="bg-primary/10 border-l-4 border-primary p-4 rounded-lg shadow-sm">
                  <div className="flex items-center">
                    <div className="w-12 h-12 bg-primary/20 rounded-lg flex items-center justify-center ml-3">
                      <ClipboardList className="text-primary w-6 h-6" />
                    </div>
                    <div>
                      <p className="text-sm text-primary">کل فرم‌ها</p>
                      <p className="text-2xl font-bold text-primary">{stats.totalForms}</p>
                    </div>
                  </div>
                </div>
                
                <div className="bg-warning/10 border-l-4 border-warning p-4 rounded-lg shadow-sm">
                  <div className="flex items-center">
                    <div className="w-12 h-12 bg-warning/20 rounded-lg flex items-center justify-center ml-3">
                      <Clock className="text-warning w-6 h-6" />
                    </div>
                    <div>
                      <p className="text-sm text-warning">در انتظار</p>
                      <p className="text-2xl font-bold text-warning">{stats.pendingForms}</p>
                    </div>
                  </div>
                </div>
                
                <div className="bg-success/10 border-l-4 border-success p-4 rounded-lg shadow-sm">
                  <div className="flex items-center">
                    <div className="w-12 h-12 bg-success/20 rounded-lg flex items-center justify-center ml-3">
                      <CheckCircle className="text-success w-6 h-6" />
                    </div>
                    <div>
                      <p className="text-sm text-success">تکمیل شده</p>
                      <p className="text-2xl font-bold text-success">{stats.completedForms}</p>
                    </div>
                  </div>
                </div>
                
                <div className="bg-info/10 border-l-4 border-info p-4 rounded-lg shadow-sm">
                  <div className="flex items-center">
                    <div className="w-12 h-12 bg-info/20 rounded-lg flex items-center justify-center ml-3">
                      <AlertTriangle className="text-info w-6 h-6" />
                    </div>
                    <div>
                      <p className="text-sm text-info">در حال بررسی</p>
                      <p className="text-2xl font-bold text-info">{stats.inProgressForms}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            {/* Forms List - Flatly Theme */}
            <div className="bg-muted rounded-lg p-4 border border-border">
              <h3 className="font-medium text-foreground mb-4">فرم‌های در انتظار تکمیل</h3>
              
              {formsLoading ? (
                <div className="text-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
                  <p className="text-muted-foreground">در حال بارگذاری فرم‌ها...</p>
                </div>
              ) : forms.length === 0 ? (
                <div className="text-center py-8">
                  <Building className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                  <p className="text-muted-foreground">هیچ فرمی یافت نشد</p>
                  <p className="text-sm text-muted-foreground/70 mt-2">
                    برای شروع، یک فرم جدید ایجاد کنید
                  </p>
                </div>
              ) : (
                <div className="space-y-3 max-h-96 overflow-y-auto">
                  {forms.map((form: Form) => (
                    <div
                      key={form.id}
                      onClick={() => handleFormClick(form.id)}
                      className="bg-card p-4 rounded-lg border border-border hover:shadow-lg transition-all cursor-pointer hover:border-primary/30"
                    >
                      <div className="flex justify-between items-center">
                        <div className="flex items-center space-x-3 space-x-reverse">
                          <div className="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center border border-primary/20">
                            <span className="text-primary font-medium text-sm">
                              {form.indicatorNumber ? form.indicatorNumber.replace('eng-', '') : form.formNumber.replace('F', '')}
                            </span>
                          </div>
                          <div>
                            <h4 className="font-medium text-card-foreground">
                              {form.indicatorNumber ? `شماره اندیکاتور ${form.indicatorNumber}` : `شماره اندیکاتور ${form.formNumber}`}
                            </h4>

                            <p className="text-xs text-muted-foreground mt-1">
                              واحد فعلی: {getDepartmentName(form.currentDepartment)}
                              {form.delegatorName && (
                                <span className="block mt-1">
                                  ارجاع دهنده: {form.delegatorName}
                                </span>
                              )}
                            </p>
                          </div>
                        </div>
                        <div className="text-left flex items-center gap-2">
                          {getStatusBadge(form.status)}
                          {user?.department === 'admin' && (
                            <Button
                              variant="destructive"
                              size="sm"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDeleteForm(form.id);
                              }}
                              className="h-8 w-8 p-0 btn-flatly-danger"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          )}
                          <div className="text-right">
                            <p className="text-xs text-muted-foreground">
                              تاریخ ایجاد: {new Date(form.createdAt).toLocaleDateString('fa-IR')}
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
