import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import {
  ArrowLeftIcon,
  EditIcon,
  CalendarIcon,
  PlusIcon,
  XIcon,
} from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { Card, CardContent } from "@/shared/common/ui/card";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Separator } from "@/shared/common/ui/separator";
import { usePlan, checkIsUnitAdmin } from "../../hooks/usePlans";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useAuth } from "@/shared/context/AuthContext";
import { useMemo, useState } from "react";
import PlanForm from "./PlanForm";

const PlanDetails = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const localizedName = useLocalizedName();
  const { user } = useAuth();
  const { yearId } = useParams();
  const [searchParams] = useSearchParams();
  const positionId = searchParams.get("positionId");

  // Check if user is unit admin
  const isUnitAdmin = useMemo(() => checkIsUnitAdmin(user), [user]);

  // State to control sub-plan form visibility
  const [showSubPlanForm, setShowSubPlanForm] = useState(false);

  // TanStack Query hook
  const { data, isLoading, isError, error, refetch } = usePlan(id || "");
  const plan = data?.data;

  if (isLoading) {
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-8 w-2/5" />
        <Card>
          <CardContent className="p-6 space-y-4">
            <Skeleton className="h-5 w-1/4" />
            <Skeleton className="h-9 w-3/5" />
            <Skeleton className="h-5 w-1/4" />
            <Skeleton className="h-9 w-3/5" />
            <Skeleton className="h-5 w-1/4" />
            <Skeleton className="h-9 w-3/5" />
          </CardContent>
        </Card>
        <div className="flex gap-4">
          <Skeleton className="h-9 w-28" />
          <Skeleton className="h-9 w-28" />
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="p-6 space-y-6">
        <Card>
          <CardContent className="p-6">
            <div className="text-red-600 text-lg mb-4">
              Error loading plan details
            </div>
            <div className="text-muted-foreground mb-4">
              {error?.message || "Failed to load plan data. Please try again."}
            </div>
            <div className="flex gap-4">
              <Button onClick={() => refetch()} variant="outline">
                Retry
              </Button>
              <Button
                variant="ghost"
                onClick={() => navigate("/performance-management/plans")}
                className="flex items-center gap-2">
                <ArrowLeftIcon className="h-4 w-4" />
                Back to List
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!plan) {
    return (
      <div className="p-6 space-y-6">
        <Card>
          <CardContent className="p-6">
            <div className="text-lg mb-4">Plan not found</div>
            <Button
              variant="ghost"
              onClick={() =>
                navigate(
                  `/performance-management/${yearId}/plans-table/${positionId}`
                )
              }
              className="flex items-center gap-2">
              <ArrowLeftIcon className="h-4 w-4" />
              Back to List
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold">Plan Details</h2>
          <p className="text-muted-foreground">Plan ID: {plan.id}</p>
        </div>
        <Button
          variant="ghost"
          onClick={() =>
            navigate(
              `/performance-management/${yearId}/plans-table/${positionId}`
            )
          }
          className="flex items-center gap-2">
          <ArrowLeftIcon className="h-4 w-4" />
          Back to List
        </Button>
      </div>

      <Card>
        <CardContent className="p-6 space-y-6">
          {/* Plan Name */}
          <div>
            <div className="text-sm text-muted-foreground mb-2">Plan Name</div>
            <div className="p-3 border rounded-md bg-muted/50">
              <div className="text-base font-semibold">
                {localizedName(plan.name)}
              </div>
            </div>
          </div>

          {/* Description */}
          <div>
            <div className="text-sm text-muted-foreground mb-2">
              Description
            </div>
            <div className="p-3 border rounded-md bg-muted/50">
              <div className="text-base">{localizedName(plan.description)}</div>
            </div>
          </div>

          {/* Plan Details */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
              <div className="text-sm text-muted-foreground mb-2">
                Calendar Year
              </div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div className="flex items-center gap-2">
                  <CalendarIcon className="h-4 w-4 text-blue-600" />
                  <div className="text-base font-semibold">
                    {plan.calendarYear}
                  </div>
                </div>
              </div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground mb-2">
                Start Date
              </div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div className="text-base">
                  {new Date(plan.startDate).toLocaleDateString()}
                </div>
              </div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground mb-2">End Date</div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div className="text-base">
                  {new Date(plan.endDate).toLocaleDateString()}
                </div>
              </div>
            </div>
          </div>

          {/* Related IDs */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <div className="text-sm text-muted-foreground mb-2">
                Position ID
              </div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div
                  className="text-base font-mono truncate"
                  title={plan.positionId}>
                  {plan.positionId}
                </div>
              </div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground mb-2">Unit ID</div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div
                  className="text-base font-mono truncate"
                  title={plan.unitId}>
                  {plan.unitId}
                </div>
              </div>
            </div>
          </div>

          <Separator />

          {/* Timestamps */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <div className="text-sm text-muted-foreground mb-2">
                Created At
              </div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div className="text-base">
                  {plan.createdAt
                    ? new Date(plan.createdAt).toLocaleString()
                    : "N/A"}
                </div>
              </div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground mb-2">
                Last Updated
              </div>
              <div className="p-3 border rounded-md bg-muted/50">
                <div className="text-base">
                  {plan.updatedAt
                    ? new Date(plan.updatedAt).toLocaleString()
                    : "N/A"}
                </div>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex justify-end pt-4 gap-4">
            <Button variant="outline" onClick={() => navigate(-1)}>
              Back to Plans
            </Button>
            {/* Show Edit button only for Unit Admins */}
            {isUnitAdmin && (
              <Button
                onClick={() =>
                  navigate(`/performance-management/plans/${id}/edit`)
                }
                className="flex items-center gap-2">
                <EditIcon className="h-4 w-4" />
                Edit Plan
              </Button>
            )}
            {/* Show Add Sub-Plan button only for Non-Unit Admins */}
            {/* {!isUnitAdmin && (
              <Button
                onClick={() => setShowSubPlanForm(!showSubPlanForm)}
                className="flex items-center gap-2 bg-gradient-to-r from-purple-500 to-violet-600 hover:from-purple-600 hover:to-violet-700 text-white">
                {showSubPlanForm ? (
                  <>
                    <XIcon className="h-4 w-4" />
                    Cancel
                  </>
                ) : (
                  <>
                    <PlusIcon className="h-4 w-4" />
                    Add Sub-Plan
                  </>
                )}
              </Button>
            )} */}
          </div>
        </CardContent>
      </Card>

      {/* Inline Sub-Plan Form */}
      {!isUnitAdmin && showSubPlanForm && (
        <Card className="border-purple-200 border-2">
          <CardContent className="p-6">
            <div className="mb-4">
              <h3 className="text-xl font-bold text-purple-700">
                Create Sub-Plan
              </h3>
              <p className="text-sm text-muted-foreground">
                Creating a sub-plan under:{" "}
                <span className="font-semibold">
                  {localizedName(plan.name)}
                </span>
              </p>
            </div>
            <Separator className="mb-6" />
            <PlanForm
              parentPlanId={id}
              onSuccess={() => {
                setShowSubPlanForm(false);
                refetch();
              }}
            />
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default PlanDetails;
