import { useState, useEffect } from "react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Loader2, ArrowLeft } from "lucide-react";
import { useToast } from "@/shared/common/ui/use-toast";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  updateEmployeePlan,
  getEmployeePlan,
  getPlansByUnit,
} from "@/performance-management/services/api/employeePlanService";

const EditEmployeePlanPage = () => {
  const { id } = useParams<{ id: string }>();
  const { toast } = useToast();
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingPlans, setIsLoadingPlans] = useState(false);

  const [plans, setPlans] = useState<any[]>([]);

  const [formData, setFormData] = useState({
    planId: "",
    employeePositionId: "",
    serviceId: "",
    timeframe: "",

    expectedQuantity: 0,
    planType: "number" as "number" | "percent",
  });

  // Fetch employee plan data when component mounts
  useEffect(() => {
    if (id) {
      fetchEmployeePlan(id);
      fetchPlans();
    }
  }, [id]);

  const fetchEmployeePlan = async (planId: string) => {
    setIsLoading(true);
    try {
      const response = await getEmployeePlan(planId);
      const plan = response.data;

      // Convert ISO dates to YYYY-MM-DD format for input fields

      setFormData({
        planId: plan.planId || "",
        employeePositionId: plan.employeePositionId || "",
        serviceId: plan.serviceId || "",
        timeframe: plan.timeframe || "",
        expectedQuantity: plan.expectedQuantity || 0,
        planType: plan.planType || "number",
      });
    } catch (error) {
      console.error("Failed to fetch employee plan:", error);
      toast({
        title: "Error",
        description: "Failed to fetch employee plan data",
        variant: "destructive",
      });
      navigate("/performance-management/employee-plans");
    } finally {
      setIsLoading(false);
    }
  };

  const fetchPlans = async () => {
    setIsLoadingPlans(true);
    try {
      const response = await getPlansByUnit("");
      const plansData = response.data?.items || [];
      setPlans(Array.isArray(plansData) ? plansData : []);
    } catch (error) {
      console.error("Failed to fetch plans:", error);
      toast({
        title: "Error",
        description: "Failed to fetch plans",
        variant: "destructive",
      });
    } finally {
      setIsLoadingPlans(false);
    }
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!id) {
      toast({
        title: "Error",
        description: "Employee plan ID is missing",
        variant: "destructive",
      });
      return;
    }

    setIsSaving(true);
    try {
      await updateEmployeePlan(id, {
        parentEmployeePlanId: formData.planId,
        employeePositionId: formData.employeePositionId,
        planId: formData.planId,
        serviceId: formData.serviceId,
        planType: formData.planType,
        expectedQuantity: Number(formData.expectedQuantity),
        timeframe: formData.timeframe,
      });

      toast({
        title: "Success",
        description: "Employee plan updated successfully",
        variant: "default",
      });

      // Navigate back to list
      navigate("/performance-management/employee-plans");
    } catch (error: any) {
      console.error("Failed to update employee plan:", error);
      const errorMessage =
        error.response?.data?.message ||
        error.message ||
        "Failed to update employee plan";
      toast({
        title: "Error",
        description: errorMessage,
        variant: "destructive",
      });
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-purple-600" />
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <div className="mb-6">
        <Button
          variant="ghost"
          onClick={() => navigate("/performance-management/employee-plans")}
          className="mb-4"
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          {t("common.back", "Back")}
        </Button>
        <h1 className="text-2xl font-bold text-gray-900">
          {t("employeePlans.editPlan", "Edit Employee Plan")}
        </h1>
        <p className="text-gray-600 mt-1">
          {t(
            "employeePlans.editDescription",
            "Update the details of this employee performance plan"
          )}
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>
            {t("employeePlans.planDetails", "Plan Details")}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Plan Selection */}
            <div className="space-y-2">
              <Label htmlFor="planId">
                {t("employeePlans.plan", "Plan")}
                <span className="text-red-500">*</span>
              </Label>
              {isLoadingPlans ? (
                <div className="flex items-center gap-2 text-gray-500">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  {t("loading", "Loading plans...")}
                </div>
              ) : plans.length > 0 ? (
                <Select
                  value={formData.planId}
                  onValueChange={(value) => handleChange("planId", value)}
                  required
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select a plan" />
                  </SelectTrigger>
                  <SelectContent>
                    {plans.map((plan: any) => (
                      <SelectItem key={plan.id} value={plan.id}>
                        {typeof plan.name === "string"
                          ? plan.name
                          : plan.name?.en || plan.name?.am || plan.id}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <p className="text-sm text-gray-500">
                  {t("employeePlans.noPlans", "No plans available")}
                </p>
              )}
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Start Date */}
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Expected Quantity */}
              <div className="space-y-2">
                <Label htmlFor="expectedQuantity">
                  {t("employeePlans.expectedQuantity", "Expected Quantity")}
                </Label>
                <Input
                  id="expectedQuantity"
                  type="number"
                  min="0"
                  step="0.01"
                  value={formData.expectedQuantity}
                  onChange={(e) =>
                    handleChange(
                      "expectedQuantity",
                      parseFloat(e.target.value) || 0
                    )
                  }
                  placeholder="Enter expected quantity"
                />
              </div>

              {/* Plan Type */}
              <div className="space-y-2">
                <Label htmlFor="planType">
                  {t("employeePlans.planType", "Plan Type")}
                </Label>
                <Select
                  value={formData.planType}
                  onValueChange={(value) => handleChange("planType", value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select plan type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="number">
                      {t("employeePlans.number", "Number")}
                    </SelectItem>
                    <SelectItem value="percent">
                      {t("employeePlans.percentage", "Percent")}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="flex justify-end gap-3 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() =>
                  navigate("/performance-management/employee-plans")
                }
                disabled={isSaving}
              >
                {t("common.cancel", "Cancel")}
              </Button>
              <Button
                type="submit"
                disabled={isSaving}
                className="bg-purple-600 hover:bg-purple-700"
              >
                {isSaving ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    {t("saving", "Saving...")}
                  </>
                ) : (
                  t("employeePlans.update", "Update Plan")
                )}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};

export default EditEmployeePlanPage;
