import { useState } from "react";
import { useForm } from "react-hook-form";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { 
  Cog, 
  Calendar, 
  Handshake, 
  Shield, 
  DollarSign, 
  FlaskConical, 
  Warehouse,
  CheckCircle,
  Edit,
  Send
} from "lucide-react";

interface FormSectionProps {
  department: string;
  departmentName: string;
  form: any;
  isCompleted: boolean;
  isActive: boolean;
  isAccessible: boolean;
  canEdit: boolean;
  onSubmit: (data: any) => void;
  isSubmitting: boolean;
}

const departmentIcons: Record<string, any> = {
  engineering: Cog,
  planning: Calendar,
  commercial: Handshake,
  quality: Shield,
  financial: DollarSign,
  laboratory: FlaskConical,
  warehouse: Warehouse,
};

export default function FormSection({
  department,
  departmentName,
  form,
  isCompleted,
  isActive,
  isAccessible,
  canEdit,
  onSubmit,
  isSubmitting,
}: FormSectionProps) {
  const [formData, setFormData] = useState({});
  const Icon = departmentIcons[department] || Cog;

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleSubmit = () => {
    onSubmit(formData);
  };

  const getStatusBadge = () => {
    if (isCompleted) {
      return (
        <Badge className="status-completed">
          <CheckCircle className="w-3 h-3 ml-1" />
          تکمیل شده
        </Badge>
      );
    }
    if (isActive) {
      return (
        <Badge className="status-in-progress">
          <Edit className="w-3 h-3 ml-1" />
          در حال تکمیل
        </Badge>
      );
    }
    return (
      <Badge variant="secondary">
        در انتظار
      </Badge>
    );
  };

  const getSectionClass = () => {
    if (!isAccessible) return "form-section disabled bg-gray-50 border border-gray-200";
    if (isCompleted) return "form-section completed bg-green-50 border-2 border-success";
    if (isActive) return "form-section active bg-blue-50 border-2 border-primary";
    return "form-section bg-gray-50 border border-gray-200";
  };

  const renderFields = () => {
    switch (department) {
      case 'engineering':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">نوع محصول</Label>
              <Input
                value={form.productType || ''}
                onChange={(e) => handleInputChange('productType', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="نوع محصول را وارد کنید"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">کدینگ محصول</Label>
              <Input
                value={form.productCode || ''}
                onChange={(e) => handleInputChange('productCode', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="کد محصول را وارد کنید"
              />
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">مشخصات فنی</Label>
              <Textarea
                value={form.technicalSpecs || ''}
                onChange={(e) => handleInputChange('technicalSpecs', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="مشخصات فنی محصول را شرح دهید"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">تاریخ ایجاد نمونه</Label>
              <Input
                value={form.sampleCreationDate || ''}
                onChange={(e) => handleInputChange('sampleCreationDate', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="۱۴۰۳/۰۸/۱۵"
              />
            </div>
          </div>
        );

      case 'planning':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">تاریخ شروع تولید</Label>
              <Input
                type="date"
                value={form.productionStartDate || ''}
                onChange={(e) => handleInputChange('productionStartDate', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">تعداد نمونه مورد نیاز</Label>
              <Input
                type="number"
                value={form.requiredSampleCount || ''}
                onChange={(e) => handleInputChange('requiredSampleCount', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="تعداد را وارد کنید"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">برنامه زمان‌بندی</Label>
              <Select
                value={form.timeSchedule || ''}
                onValueChange={(value) => handleInputChange('timeSchedule', value)}
                disabled={isCompleted || !canEdit}
              >
                <SelectTrigger className={isCompleted || !canEdit ? "bg-gray-100" : ""}>
                  <SelectValue placeholder="انتخاب کنید" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="urgent">فوری (1-2 روز)</SelectItem>
                  <SelectItem value="normal">معمولی (1 هفته)</SelectItem>
                  <SelectItem value="non_urgent">غیرفوری (2-3 هفته)</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">اولویت تولید</Label>
              <Select
                value={form.productionPriority || ''}
                onValueChange={(value) => handleInputChange('productionPriority', value)}
                disabled={isCompleted || !canEdit}
              >
                <SelectTrigger className={isCompleted || !canEdit ? "bg-gray-100" : ""}>
                  <SelectValue placeholder="انتخاب کنید" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="high">بالا</SelectItem>
                  <SelectItem value="medium">متوسط</SelectItem>
                  <SelectItem value="low">پایین</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">توضیحات برنامه‌ریزی</Label>
              <Textarea
                value={form.planningComments || ''}
                onChange={(e) => handleInputChange('planningComments', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="توضیحات اضافی در صورت نیاز"
              />
            </div>
          </div>
        );

      case 'commercial':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">اطلاعات تامین‌کننده</Label>
              <Input
                value={form.supplierInfo || ''}
                onChange={(e) => handleInputChange('supplierInfo', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="نام و اطلاعات تامین‌کننده"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">برآورد هزینه</Label>
              <Input
                value={form.estimatedCost || ''}
                onChange={(e) => handleInputChange('estimatedCost', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="مبلغ برآوردی"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">زمان تحویل</Label>
              <Input
                value={form.deliveryTime || ''}
                onChange={(e) => handleInputChange('deliveryTime', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="مدت زمان تحویل"
              />
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">شرایط تجاری</Label>
              <Textarea
                value={form.commercialTerms || ''}
                onChange={(e) => handleInputChange('commercialTerms', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="شرایط پرداخت، گارانتی و سایر موارد"
              />
            </div>
          </div>
        );

      case 'quality':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">استانداردهای کیفی</Label>
              <Input
                value={form.qualityStandards || ''}
                onChange={(e) => handleInputChange('qualityStandards', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="استانداردهای مورد نیاز"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">الزامات تست</Label>
              <Input
                value={form.testingRequirements || ''}
                onChange={(e) => handleInputChange('testingRequirements', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="تست‌های مورد نیاز"
              />
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">چک‌لیست کیفیت</Label>
              <Textarea
                value={form.qualityChecklist || ''}
                onChange={(e) => handleInputChange('qualityChecklist', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="موارد بررسی کیفیت"
              />
            </div>
          </div>
        );

      case 'financial':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">بودجه تخصیص یافته</Label>
              <Input
                value={form.allocatedBudget || ''}
                onChange={(e) => handleInputChange('allocatedBudget', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="مبلغ بودجه"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">مرکز هزینه</Label>
              <Input
                value={form.costCenter || ''}
                onChange={(e) => handleInputChange('costCenter', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="کد مرکز هزینه"
              />
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">یادداشت‌های مالی</Label>
              <Textarea
                value={form.financialNotes || ''}
                onChange={(e) => handleInputChange('financialNotes', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="توضیحات و یادداشت‌های مالی"
              />
            </div>
          </div>
        );

      case 'laboratory':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">تاریخ تست</Label>
              <Input
                value={form.testDate || ''}
                onChange={(e) => handleInputChange('testDate', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="تاریخ انجام تست"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">پروتکل تست</Label>
              <Input
                value={form.testProtocol || ''}
                onChange={(e) => handleInputChange('testProtocol', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="شماره پروتکل"
              />
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">نتایج تست</Label>
              <Textarea
                value={form.testResults || ''}
                onChange={(e) => handleInputChange('testResults', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="نتایج و مشاهدات تست"
              />
            </div>
          </div>
        );

      case 'warehouse':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">محل انبارداری</Label>
              <Input
                value={form.storageLocation || ''}
                onChange={(e) => handleInputChange('storageLocation', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="محل نگهداری"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">کد موجودی</Label>
              <Input
                value={form.inventoryCode || ''}
                onChange={(e) => handleInputChange('inventoryCode', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="کد رهگیری موجودی"
              />
            </div>
            <div>
              <Label className="block text-sm font-medium text-gray-700 mb-2">تعداد دریافتی</Label>
              <Input
                type="number"
                value={form.receivedQuantity || ''}
                onChange={(e) => handleInputChange('receivedQuantity', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                placeholder="تعداد دریافت شده"
              />
            </div>
            <div className="md:col-span-2">
              <Label className="block text-sm font-medium text-gray-700 mb-2">یادداشت‌های انبار</Label>
              <Textarea
                value={form.warehouseNotes || ''}
                onChange={(e) => handleInputChange('warehouseNotes', e.target.value)}
                className={isCompleted || !canEdit ? "bg-gray-100" : ""}
                readOnly={isCompleted || !canEdit}
                rows={3}
                placeholder="توضیحات و یادداشت‌های انبار"
              />
            </div>
          </div>
        );

      default:
        return <p className="text-gray-500 text-sm">این بخش در حال توسعه است.</p>;
    }
  };

  return (
    <Card className={getSectionClass()}>
      <CardContent className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold flex items-center">
            <Icon className="ml-3 w-5 h-5" />
            {departmentName}
          </h3>
          {getStatusBadge()}
        </div>
        
        {!isAccessible ? (
          <p className="text-gray-500 text-sm">
            این بخش پس از تکمیل مراحل قبلی فعال خواهد شد.
          </p>
        ) : (
          <>
            {renderFields()}
            
            {canEdit && isActive && !isCompleted && (
              <div className="flex justify-end mt-6">
                <Button
                  onClick={handleSubmit}
                  disabled={isSubmitting}
                  className="font-medium"
                >
                  <Send className="w-4 h-4 ml-2" />
                  {isSubmitting ? "در حال ارسال..." : "تکمیل و ارسال به واحد بعدی"}
                </Button>
              </div>
            )}
          </>
        )}
      </CardContent>
    </Card>
  );
}
