import { useState } from "react";
import { ChevronDown } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import EngineeringForm from "./EngineeringForm";
import PlanningForm from "./PlanningForm";
import CommercialForm from "./CommercialForm";
import QualityForm from "./QualityForm";
import FinancialForm from "./FinancialForm";
import LaboratoryForm from "./LaboratoryForm";
import WarehouseForm from "./WarehouseForm";

interface DepartmentAccordionProps {
  formId: string;
  formData: any;
  userCanEdit: boolean;
  onFormUpdate?: () => void;
  onArchive?: (data: any) => void;
}

interface DepartmentSection {
  key: string;
  name: string;
  component: React.ComponentType<any>;
  isActive: boolean;
  isCompleted: boolean;
}

export default function DepartmentAccordion({ 
  formId, 
  formData, 
  userCanEdit,
  onFormUpdate,
  onArchive 
}: DepartmentAccordionProps) {
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});

  const departments: DepartmentSection[] = [
    {
      key: 'engineering',
      name: 'واحد مهندسی',
      component: EngineeringForm,
      isActive: formData.currentDepartment === 'engineering',
      isCompleted: formData.engineeringCompleted
    },
    {
      key: 'planning',
      name: 'واحد برنامه‌ریزی',
      component: PlanningForm,
      isActive: formData.currentDepartment === 'planning',
      isCompleted: formData.planningCompleted
    },
    {
      key: 'commercial',
      name: 'واحد بازرگانی',
      component: CommercialForm,
      isActive: formData.currentDepartment === 'commercial',
      isCompleted: formData.commercialCompleted
    },
    {
      key: 'quality',
      name: 'واحد تضمین کیفیت',
      component: QualityForm,
      isActive: formData.currentDepartment === 'quality',
      isCompleted: formData.qualityCompleted
    },
    {
      key: 'financial',
      name: 'واحد مالی',
      component: FinancialForm,
      isActive: formData.currentDepartment === 'financial',
      isCompleted: formData.financialCompleted
    },
    {
      key: 'laboratory',
      name: 'تست آزمایشگاهی',
      component: LaboratoryForm,
      isActive: formData.currentDepartment === 'laboratory',
      isCompleted: formData.laboratoryCompleted
    },
    {
      key: 'warehouse',
      name: 'واحد انبار',
      component: WarehouseForm,
      isActive: formData.currentDepartment === 'warehouse',
      isCompleted: formData.warehouseCompleted
    }
  ];

  const toggleSection = (sectionKey: string) => {
    setExpandedSections(prev => ({
      ...prev,
      [sectionKey]: !prev[sectionKey]
    }));
  };

  const getStatusColor = (dept: DepartmentSection) => {
    if (dept.isCompleted) {
      return 'bg-green-500';
    } else if (dept.isActive) {
      return 'bg-yellow-500';
    } else {
      return 'bg-gray-400';
    }
  };

  const getDepartmentData = (deptKey: string) => {
    switch (deptKey) {
      case 'engineering':
        return {
          suggestedSupplier: formData.suggestedSupplier,
          drawingCode: formData.drawingCode,
          sentDocuments: formData.sentDocuments,
          documentSendDate: formData.documentSendDate,
          needDate: formData.needDate,
          productName: formData.productName,
          supplyExecutive: formData.supplyExecutive,
          supplyOrder: formData.supplyOrder,
          newProductDevPhase: formData.newProductDevPhase,
          issueReason: formData.issueReason,
          indicatorNumber: formData.indicatorNumber,
          actionNumber: formData.actionNumber,
          engineeringDate: formData.engineeringDate,
          previousFormIndicator: formData.previousFormIndicator,
          projectCostCenterCode: formData.projectCostCenterCode,
          expertApproval: formData.expertApproval,
          managerApproval: formData.managerApproval,
          expertApprovalImageUrl: formData.expertApprovalImageUrl,
          managerApprovalImageUrl: formData.managerApprovalImageUrl,
        };
      case 'planning':
        return {
          planningExecutionDate: formData.planningExecutionDate,
          planningManagerApproval: formData.planningManagerApproval,
          planningManagerApprovalImageUrl: formData.planningManagerApprovalImageUrl,
        };
      case 'commercial':
        return {
          commercialSupplierNameCode: formData.commercialSupplierNameCode,
          commercialSampleSendDate: formData.commercialSampleSendDate,
          commercialBillNumber: formData.commercialBillNumber,
          commercialShipmentCode: formData.commercialShipmentCode,
          commercialContractorCertificate: formData.commercialContractorCertificate,
          commercialExpertApproval: formData.commercialExpertApproval,
          commercialManagerApproval: formData.commercialManagerApproval,
          commercialExpertApprovalImageUrl: formData.commercialExpertApprovalImageUrl,
          commercialManagerApprovalImageUrl: formData.commercialManagerApprovalImageUrl,
        };
      case 'quality':
        return {
          qualityExecutionDate: formData.qualityExecutionDate,
          qualityManagerApproval: formData.qualityManagerApproval,
          qualityManagerApprovalImageUrl: formData.qualityManagerApprovalImageUrl,
        };
      case 'financial':
        return {
          financialExecutionDate: formData.financialExecutionDate,
          financialExpertApproval: formData.financialExpertApproval,
          financialExpertApprovalImageUrl: formData.financialExpertApprovalImageUrl,
        };
      case 'laboratory':
        return {
          laboratorySpecialStorageConditions: formData.laboratorySpecialStorageConditions,
          laboratoryExecutionDate: formData.laboratoryExecutionDate,
          laboratoryFinalStatus: formData.laboratoryFinalStatus,
          laboratoryTestRequestNumber: formData.laboratoryTestRequestNumber,
          laboratoryTestRequestDate: formData.laboratoryTestRequestDate,
          laboratoryExpertApproval: formData.laboratoryExpertApproval,
          laboratoryManagerApproval: formData.laboratoryManagerApproval,
          laboratoryExpertApprovalImageUrl: formData.laboratoryExpertApprovalImageUrl,
          laboratoryManagerApprovalImageUrl: formData.laboratoryManagerApprovalImageUrl,
          dimensionalPartName: formData.dimensionalPartName,
          dimensionalLotCode: formData.dimensionalLotCode,
          dimensionalDrawingTestNumber: formData.dimensionalDrawingTestNumber,
          dimensionalSupplier: formData.dimensionalSupplier,
          dimensionalSampleSupplyNumber: formData.dimensionalSampleSupplyNumber,
          dimensionalSpecialStorageConditions: formData.dimensionalSpecialStorageConditions,
          dimensionalLotStatus: formData.dimensionalLotStatus,
        };
      case 'warehouse':
        return {
          warehouseDeliveryDate: formData.warehouseDeliveryDate,
          warehouseHealthyCount: formData.warehouseHealthyCount,
          warehouseHealthyUnit: formData.warehouseHealthyUnit,
          warehouseWasteCount: formData.warehouseWasteCount,
          warehouseWasteUnit: formData.warehouseWasteUnit,
          warehouseExpertApproval: formData.warehouseExpertApproval,
          warehouseExpertApprovalImageUrl: formData.warehouseExpertApprovalImageUrl,
        };
      default:
        return {};
    }
  };

  return (
    <div className="space-y-2">
      {departments.map((dept) => {
        const isExpanded = expandedSections[dept.key];
        const Component = dept.component;
        const departmentData = getDepartmentData(dept.key);

        return (
          <Card key={dept.key} className="overflow-hidden minty-card">
            <Button
              variant="ghost"
              className="w-full h-auto p-0 hover:opacity-90 transition-opacity"
              onClick={() => toggleSection(dept.key)}
            >
              <div className="flex items-center justify-between w-full p-4 minty-primary text-white">
                <div className="flex items-center gap-3">
                  <div className={`w-3 h-3 rounded-full ${getStatusColor(dept)}`} />
                  <span className="font-medium text-lg">{dept.name}</span>
                </div>
                <ChevronDown 
                  className={`w-5 h-5 transition-transform duration-200 ${
                    isExpanded ? 'rotate-180' : ''
                  }`} 
                />
              </div>
            </Button>
            
            {isExpanded && (
              <CardContent className="p-6 bg-gray-50">
                {dept.key === 'engineering' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    partsData={formData.partsTable || []}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
                {dept.key === 'planning' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    monitoringData={formData.planningMonitoringTable || []}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
                {dept.key === 'commercial' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    receivedData={formData.commercialReceivedTable || []}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
                {dept.key === 'quality' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    partsData={formData.qualityPartsTable || []}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
                {dept.key === 'financial' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    codeData={formData.financialCodeTable || []}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
                {dept.key === 'laboratory' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    testsData={formData.laboratoryTestsTable || []}
                    partsData={formData.partsTable || []}
                    partsStatusData={formData.laboratoryPartsStatusTable || []}
                    dimensionalMeasurementsData={formData.dimensionalMeasurementsTable || []}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
                {dept.key === 'warehouse' && (
                  <Component
                    formId={formId}
                    initialData={departmentData}
                    onSave={onFormUpdate}
                    onSubmit={onFormUpdate}
                    onArchive={onArchive || onFormUpdate}
                    isLoading={false}
                    canEdit={userCanEdit}
                  />
                )}
              </CardContent>
            )}
          </Card>
        );
      })}
    </div>
  );
}