"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { useAuth } from "@/lib/auth-context";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RichTextEditor } from "@/components/ui/rich-text-editor";
import { Checkbox } from "@/components/ui/checkbox";
import { DashboardBreadcrumb } from "@/components/dashboard/dashboard-breadcrumb";
import { cn } from "@/lib/utils";
import { ArrowLeft, Loader2, Send } from "lucide-react";
import Link from "next/link";
import { toast } from "react-toastify";

const reportMonths = [
  { value: 1, label: "January" },
  { value: 2, label: "February" },
  { value: 3, label: "March" },
  { value: 4, label: "April" },
  { value: 5, label: "May" },
  { value: 6, label: "June" },
  { value: 7, label: "July" },
  { value: 8, label: "August" },
  { value: 9, label: "September" },
  { value: 10, label: "October" },
  { value: 11, label: "November" },
  { value: 12, label: "December" },
];

function formatReportMonth(year: number, month: number) {
  return `${year}-${String(month).padStart(2, "0")}`;
}

type ReportLocationOption = {
  uuid?: string | null;
  title?: string | null;
  name?: string | null;
  district_name?: string | null;
  status?: string | null;
  district?: ReportLocationOption | null;
};

type GuideRegistrationOptionsResponse = {
  success?: boolean;
  data?: {
    locations?: ReportLocationOption[];
  };
  message?: string;
  message_hi?: string;
};

type MonthlyReportSubmitResponse = {
  success?: boolean;
  message?: string;
  message_hi?: string;
};

function optionValue(option: ReportLocationOption) {
  return option.uuid || "";
}

function optionLabel(option: ReportLocationOption) {
  return (
    option.title ||
    option.name ||
    option.district_name ||
    option.district?.title ||
    option.district?.name ||
    option.district?.district_name ||
    option.uuid ||
    ""
  );
}

function activeLocationOptions(options?: ReportLocationOption[]) {
  return (options || []).filter(
    (option) => option.status !== "inactive" && optionValue(option),
  );
}

export default function NewReportPage() {
  const router = useRouter();
  const { token } = useAuth();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [locationOptions, setLocationOptions] = useState<
    ReportLocationOption[]
  >([]);
  const [isLoadingLocations, setIsLoadingLocations] = useState(true);

  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1;
  const allowedReportMonths = Array.from({ length: 4 }, (_, index) => {
    const date = new Date(currentYear, currentMonth - 1 - index, 1);

    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
    };
  });
  const defaultMonth = formatReportMonth(currentYear, currentMonth);

  const [formData, setFormData] = useState({
    month: defaultMonth,
    toursCount: "",
    touristsServed: "",
    revenue: "",
    locations: [] as string[],
    feedback: "",
  });

  useEffect(() => {
    let isMounted = true;

    const loadLocations = async () => {
      setIsLoadingLocations(true);

      try {
        const activeToken = token || localStorage.getItem("auth_token");
        const response = await apiRequest(
          apiUrl("/guide-registration/options"),
          {
            headers: {
              Authorization: `Bearer ${activeToken || ""}`,
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          },
        );
        const result =
          (await response.json()) as GuideRegistrationOptionsResponse;

        if (!response.ok || result.success === false) {
          throw new Error(
            getLocalizedApiMessage(result, "Failed to load service locations."),
          );
        }

        if (isMounted) {
          setLocationOptions(activeLocationOptions(result.data?.locations));
        }
      } catch (error) {
        if (isMounted) {
          toast.error(
            error instanceof Error
              ? error.message
              : "Failed to load service locations.",
          );
          setLocationOptions([]);
        }
      } finally {
        if (isMounted) {
          setIsLoadingLocations(false);
        }
      }
    };

    loadLocations();

    return () => {
      isMounted = false;
    };
  }, [token]);
  const selectedYear = Number(formData.month.slice(0, 4)) || currentYear;
  const selectedMonth = Number(formData.month.slice(5, 7)) || currentMonth;
  const yearOptions = Array.from(
    new Set(allowedReportMonths.map((period) => period.year)),
  );
  const isAllowedReportMonth = allowedReportMonths.some(
    (period) => period.year === selectedYear && period.month === selectedMonth,
  );
  const isAllowedMonthForSelectedYear = (month: number) =>
    allowedReportMonths.some(
      (period) => period.year === selectedYear && period.month === month,
    );

  const updateReportYear = (year: number) => {
    const nextPeriod = allowedReportMonths.find(
      (period) => period.year === year,
    );

    if (!nextPeriod) return;

    setFormData((prev) => ({
      ...prev,
      month: formatReportMonth(nextPeriod.year, nextPeriod.month),
    }));
  };

  const updateReportMonth = (month: number) => {
    const nextPeriod = allowedReportMonths.find(
      (period) => period.year === selectedYear && period.month === month,
    );

    if (!nextPeriod) return;

    setFormData((prev) => ({
      ...prev,
      month: formatReportMonth(nextPeriod.year, nextPeriod.month),
    }));
  };

  const toggleLocation = (location: string) => {
    setFormData((prev) => ({
      ...prev,
      locations: prev.locations.includes(location)
        ? prev.locations.filter((l) => l !== location)
        : [...prev.locations, location],
    }));
  };

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

    if (!isValid) {
      toast.error("Please fill all required report details.");
      return;
    }

    setIsSubmitting(true);

    try {
      const activeToken = token || localStorage.getItem("auth_token");
      const payload = {
        report_month: formData.month,
        number_of_tours: Number(formData.toursCount),
        tourists_served: Number(formData.touristsServed),
        revenue: formData.revenue ? Number(formData.revenue) : 0,
        location_uuids: formData.locations,
        tourist_feedback: formData.feedback,
        status: "Submitted",
      };
      const response = await apiRequest(apiUrl("/guide/monthly-reports"), {
        method: "POST",
        headers: {
          Authorization: `Bearer ${activeToken || ""}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });
      const result = (await response.json()) as MonthlyReportSubmitResponse;

      if (!response.ok || result.success === false) {
        throw new Error(
          getLocalizedApiMessage(result, "Monthly report submission failed."),
        );
      }

      toast.success(
        getLocalizedApiMessage(
          result,
          "Monthly report submitted successfully.",
        ),
      );
      router.push("/dashboard/reports");
    } catch (error) {
      toast.error(
        error instanceof Error
          ? error.message
          : "Unable to submit monthly report.",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const isValid =
    formData.month &&
    isAllowedReportMonth &&
    formData.toursCount &&
    formData.touristsServed &&
    !isLoadingLocations &&
    formData.locations.length > 0;

  return (
    <div className="w-full space-y-5">
      <DashboardBreadcrumb
        current="Submit Report"
        parent="Monthly Reports"
        parentHref="/dashboard/reports"
      />

      <div className="flex items-center gap-4 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm">
        <Link href="/dashboard/reports">
          <Button variant="outline" size="icon" className="rounded-full">
            <ArrowLeft className="h-5 w-5" />
          </Button>
        </Link>
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Submit Monthly Report
          </h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Report your tour activities for the month
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
          <CardHeader className="px-5 pt-5">
            <CardTitle className="text-xl font-black">
              Add Report Details
            </CardTitle>
            <CardDescription>
              Provide details about your tour activities
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6 p-5 pt-2 xl:p-6 xl:pt-2">
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Report Year *</Label>
                <div className="flex flex-wrap gap-2">
                  {yearOptions.map((year) => {
                    const isSelected = selectedYear === year;

                    return (
                      <button
                        key={year}
                        type="button"
                        onClick={() => updateReportYear(year)}
                        className={cn(
                          "h-10 rounded-full border px-4 text-sm font-bold transition-colors",
                          isSelected
                            ? "border-[var(--theme-primary)] bg-[var(--theme-primary)] text-white shadow-sm"
                            : "border-[var(--theme-border)] bg-[var(--theme-surface-soft)] text-foreground hover:bg-[var(--theme-surface-strong)]",
                        )}
                      >
                        {year}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="space-y-2">
                <Label>Report Month *</Label>
                <div className="flex flex-wrap gap-2">
                  {reportMonths.map((month) => {
                    const isAllowedMonth = isAllowedMonthForSelectedYear(
                      month.value,
                    );
                    const isSelected = selectedMonth === month.value;

                    return (
                      <button
                        key={`${selectedYear}-${month.value}`}
                        type="button"
                        disabled={!isAllowedMonth}
                        onClick={() => updateReportMonth(month.value)}
                        className={cn(
                          "h-10 rounded-full border px-4 text-sm font-bold transition-colors",
                          isSelected
                            ? "border-[var(--theme-primary)] bg-[var(--theme-primary)] text-white shadow-sm"
                            : "border-[var(--theme-border)] bg-[var(--theme-surface-soft)] text-foreground hover:bg-[var(--theme-surface-strong)]",
                          !isAllowedMonth &&
                            "cursor-not-allowed border-slate-200 bg-slate-100 text-slate-400 opacity-70 hover:bg-slate-100",
                        )}
                      >
                        {month.label}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>

            <div className="grid gap-4 sm:grid-cols-3">
              <div className="space-y-2">
                <Label htmlFor="toursCount">Number of Tours *</Label>
                <Input
                  id="toursCount"
                  type="number"
                  placeholder="e.g., 10"
                  value={formData.toursCount}
                  onChange={(e) =>
                    setFormData({ ...formData, toursCount: e.target.value })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="touristsServed">Tourists Served *</Label>
                <Input
                  id="touristsServed"
                  type="number"
                  placeholder="e.g., 50"
                  value={formData.touristsServed}
                  onChange={(e) =>
                    setFormData({ ...formData, touristsServed: e.target.value })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="revenue">Revenue (INR)</Label>
                <Input
                  id="revenue"
                  type="number"
                  placeholder="e.g., 35000"
                  value={formData.revenue}
                  onChange={(e) =>
                    setFormData({ ...formData, revenue: e.target.value })
                  }
                />
              </div>
            </div>

            <div className="space-y-3">
              <Label>Service Locations Visited *</Label>
              {isLoadingLocations ? (
                <div className="flex items-center gap-2 rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-3 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Loading service locations...
                </div>
              ) : locationOptions.length ? (
                <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                  {locationOptions.map((location) => {
                    const value = optionValue(location);
                    const label = optionLabel(location);

                    return (
                      <label
                        key={value}
                        className="flex cursor-pointer items-center gap-3 rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-2 hover:bg-[var(--theme-surface-strong)]"
                      >
                        <Checkbox
                          checked={formData.locations.includes(value)}
                          onCheckedChange={() => toggleLocation(value)}
                        />
                        <span className="text-sm">{label}</span>
                      </label>
                    );
                  })}
                </div>
              ) : (
                <div className="rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-3 text-sm text-muted-foreground">
                  No service locations available.
                </div>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="feedback">Tourist Feedback / Notes</Label>
              <RichTextEditor
                id="feedback"
                value={formData.feedback}
                onChange={(value) =>
                  setFormData({ ...formData, feedback: value })
                }
                placeholder="Share any notable feedback from tourists or important observations..."
                minHeightClassName="min-h-[160px]"
              />
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end gap-4 mt-6">
          <Link href="/dashboard/reports">
            <Button type="button" variant="outline">
              Cancel
            </Button>
          </Link>
          <Button type="submit" disabled={!isValid || isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Submitting...
              </>
            ) : (
              <>
                <Send className="h-4 w-4 mr-2" />
                Submit Report
              </>
            )}
          </Button>
        </div>
      </form>
    </div>
  );
}
