import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useRoute } from "wouter";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { apiRequest } from "@/lib/queryClient";
import { useLocation } from "wouter";
import { isUnauthorizedError } from "@/lib/authUtils";
import { ArrowRight } from "lucide-react";
import ProgressIndicator from "@/components/ProgressIndicator";
import FormSection from "@/components/FormSection";
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";
import FormDelegation from "@/components/FormDelegation";
import DepartmentAccordion from "@/components/DepartmentAccordion";

interface Form {
  id: string;
  formNumber: string;
  currentDepartment: string;
  status: string;
  createdAt: string;
  // All department fields
  [key: string]: any;
}

export default function FormView() {
  const [match, params] = useRoute("/form/:id");
  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 form data
  const { data: form, isLoading: formLoading } = useQuery<Form>({
    queryKey: ["/api/forms", params?.id],
    enabled: !!params?.id,
    retry: false,
  });

  // Complete form section mutation
  const completeFormMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("PUT", `/api/forms/${params?.id}/complete`, {
        data,
      });
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "بخش فرم با موفقیت تکمیل شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms", params?.id] });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
    },
    onError: (error: any) => {
      // Don't show 403 errors (access denied) - they're expected after delegation
      if (error.status === 403) {
        // Silently redirect to home instead of showing error
        setLocation("/");
        return;
      }
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: error.message || "خطا در تکمیل بخش فرم",
        variant: "destructive",
      });
    },
  });

  // Forward form mutation
  const forwardFormMutation = useMutation({
    mutationFn: async (notes?: string) => {
      const response = await apiRequest("PUT", `/api/forms/${params?.id}/forward`, {
        notes,
      });
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "فرم با موفقیت به واحد بعدی ارسال شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms", params?.id] });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
      setLocation("/");
    },
    onError: (error: any) => {
      // Don't show 403 errors (access denied) - they're expected after delegation
      if (error.status === 403) {
        // Silently redirect to home instead of showing error
        setLocation("/");
        return;
      }
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: error.message || "خطا در ارسال فرم",
        variant: "destructive",
      });
    },
  });

  // Archive form mutation  
  const archiveFormMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("POST", `/api/forms/${params?.id}/archive`, {
        data,
      });
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "فرم با موفقیت بایگانی شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/forms", params?.id] });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
      queryClient.invalidateQueries({ queryKey: ["/api/dashboard/stats"] });
      setLocation("/");
    },
    onError: (error: any) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: error.message || "خطا در بایگانی فرم",
        variant: "destructive",
      });
    },
  });

  const handleCompleteAndForward = (data: any) => {
    completeFormMutation.mutate(data, {
      onSuccess: () => {
        const departmentNames: Record<string, string> = {
          engineering: 'مهندسی',
          planning: 'برنامه‌ریزی',
          commercial: 'بازرگانی',
          quality: 'تضمین کیفیت',
          financial: 'مالی',
          laboratory: 'تست آزمایشگاهی',
          warehouse: 'انبار'
        };
        const currentDeptName = departmentNames[form?.currentDepartment || ''] || form?.currentDepartment;
        forwardFormMutation.mutate(`تکمیل شده توسط واحد ${currentDeptName}`);
      },
    });
  };

  const handleBackToDashboard = () => {
    setLocation("/");
  };

  if (authLoading || formLoading) {
    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 || !form) {
    return null;
  }

  const departments = [
    'engineering',
    'planning', 
    'commercial',
    'quality',
    'financial',
    'laboratory',
    'warehouse'
  ];

  const departmentNames: Record<string, string> = {
    engineering: 'مهندسی',
    planning: 'برنامه‌ریزی',
    commercial: 'بازرگانی',
    quality: 'تضمین کیفیت',
    financial: 'مالی',
    laboratory: 'تست آزمایشگاهی',
    warehouse: 'انبار'
  };

  const currentDeptIndex = departments.indexOf(form.currentDepartment);
  
  // Check if user can edit based on department access, assignment, or admin role
  // Archived forms cannot be edited by anyone
  const userDepartmentAccess = Array.isArray((user as any).departmentAccess) ? (user as any).departmentAccess : [];
  const userCanEdit = (form.currentDepartment !== 'archived' && form.status !== 'completed') && 
                      (form.currentDepartment === user.department || 
                       userDepartmentAccess.includes(form.currentDepartment) ||
                       form.assignedToUserId === user.id ||
                       user.department === 'admin');

  return (
    <div className="min-h-screen bg-gray-50 page-transition compact-view">
      {/* Header */}
      <header className="bg-white shadow-sm border-b border-gray-200">
        <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>
              <h1 className="text-lg font-semibold text-gray-900">
                فرم تامین نمونه کالای جدید
              </h1>
              <p className="text-sm text-gray-500">
                {form.indicatorNumber && form.indicatorNumber !== '0' ? `شماره اندیکاتور: ${form.indicatorNumber}` : `شماره فرم: ${form.formNumber}`}
              </p>
            </div>
            <Button
              variant="ghost"
              onClick={handleBackToDashboard}
              className="text-gray-500 hover:text-gray-700"
            >
              <ArrowRight className="w-4 h-4 ml-2" />
              بازگشت به داشبورد
            </Button>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Card>
          <CardContent className="p-6">
            {/* Progress Indicator */}
            <ProgressIndicator
              departments={departments}
              departmentNames={departmentNames}
              currentDepartment={form.currentDepartment}
              completedDepartments={departments.filter(dept => form[`${dept}Completed`])}
            />
            
            {/* Department Accordion */}
            <div className="mt-8">
              <DepartmentAccordion
                formId={form.id}
                formData={form}
                userCanEdit={userCanEdit}
                onFormUpdate={() => {
                  queryClient.invalidateQueries({ queryKey: ["/api/forms", params?.id] });
                }}
                onArchive={(data) => {
                  archiveFormMutation.mutate(data);
                }}
              />
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
