import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { LoanOptionGroup } from "@/components/ui/loan-option-group";
import {
  CurrencyInputWithSlider,
  AddressAutocomplete,
} from "@/components/ui/form-primitives";
import {
  Accordion,
  AccordionItem,
  AccordionTrigger,
  AccordionContent,
} from "@/components/ui/accordion";
import { IncomeBarChart } from "@/components/ui/income-bar-chart";
import type { IncomeBarChartData } from "@/components/ui/income-bar-chart";
import { FREQUENCY_OPTIONS } from "@/lib/loan-constants";
import { formatCurrency } from "@/lib/format-currency";

// ─── Constants ────────────────────────────────────────────────────────────────

const EMPLOYMENT_TYPE_OPTIONS = [
  { value: "payg", label: "PAYG" },
  { value: "self-employed", label: "Self Employed" },
  { value: "unemployed", label: "Unemployed" },
  { value: "retired", label: "Retired" },
];

const EMPLOYMENT_STATUS_OPTIONS = [
  { value: "primary", label: "Primary" },
  { value: "secondary", label: "Secondary" },
];

const EMPLOYMENT_BASIS_OPTIONS = [
  { value: "contract", label: "Contract" },
  { value: "temporary", label: "Temporary" },
  { value: "casual", label: "Casual" },
];

// ─── Types ────────────────────────────────────────────────────────────────────

export type IncomeEmploymentType =
  | "payg"
  | "self-employed"
  | "unemployed"
  | "retired";

export type IncomeEmploymentStatus = "primary" | "secondary";

export type IncomeEmploymentBasis =
  | "contract"
  | "temporary"
  | "casual"
  | "full-time"
  | "part-time";

export type IncomeFrequency = "monthly" | "weekly";

export type IncomeCompanyType = "public" | "private";

export type IncomeWorkSource = {
  id: string;
  /** Accordion header label — defaults to "Main Income Source" */
  label?: string;
  employmentType?: IncomeEmploymentType;
  employmentStatus?: IncomeEmploymentStatus;
  employmentBasis?: IncomeEmploymentBasis;
  jobTitle?: string;
  startDate?: string;
  /** Whether still in this position — when false, endDate is required */
  stillInPosition?: boolean;
  endDate?: string;
  companyName?: string;
  companyAddress?: string;
  incomeAmount?: number;
  incomeFrequency?: IncomeFrequency;
  companyType?: IncomeCompanyType;
};

export type IncomeWorkDetailsProps = {
  /** Rendered as "{applicantName} Income" in the heading */
  applicantName: string;
  /** Total from Open Banking — shown in summary card above the chart */
  totalIncome?: number;
  /** Monthly income data for the IncomeBarChart */
  incomeData?: IncomeBarChartData | null;
  /** Work Details accordion sources */
  sources: IncomeWorkSource[];
  onSourceChange?: (id: string, updates: Partial<IncomeWorkSource>) => void;
  onAddSource?: () => void;
  /** "Add More Account +" button in the summary card */
  onConnectMore?: () => void;
  className?: string;
};

// ─── Income source form ───────────────────────────────────────────────────────

function IncomeSourceForm({
  source,
  onChange,
}: {
  source: IncomeWorkSource;
  onChange: (updates: Partial<IncomeWorkSource>) => void;
}) {
  return (
    <div className="flex flex-col gap-4 pt-2">
      {/* Employment type */}
      <LoanOptionGroup
        options={EMPLOYMENT_TYPE_OPTIONS}
        value={source.employmentType ?? ""}
        onChange={(v) => {
          if (typeof v === "string")
            onChange({ employmentType: v as IncomeEmploymentType });
        }}
      />

      {/* Employment Status */}
      <LoanOptionGroup
        title="Employment Status"
        options={EMPLOYMENT_STATUS_OPTIONS}
        value={source.employmentStatus ?? ""}
        onChange={(v) => {
          if (typeof v === "string")
            onChange({ employmentStatus: v as IncomeEmploymentStatus });
        }}
      />

      {/* Employment Type (basis) */}
      <LoanOptionGroup
        title="Employment Type"
        options={EMPLOYMENT_BASIS_OPTIONS}
        value={source.employmentBasis ?? ""}
        onChange={(v) => {
          if (typeof v === "string")
            onChange({ employmentBasis: v as IncomeEmploymentBasis });
        }}
      />

      {/* Job Title */}
      <div className="flex flex-col gap-1.5">
        <label className="text-label-small text-muted-foreground">
          Job Title
        </label>
        <Input
          value={source.jobTitle ?? ""}
          onChange={(e) => onChange({ jobTitle: e.target.value })}
          placeholder="e.g. Software Engineer"
        />
      </div>

      {/* Start Date + optional End Date (shown side-by-side when not still in position) */}
      <div
        className={
          source.stillInPosition === false
            ? "grid grid-cols-2 gap-3"
            : undefined
        }
      >
        <div className="flex flex-col gap-1.5">
          <label className="text-label-small text-muted-foreground">
            Start Date
          </label>
          <Input
            type="date"
            value={source.startDate ?? ""}
            onChange={(e) => onChange({ startDate: e.target.value })}
          />
        </div>
        {source.stillInPosition === false && (
          <div className="flex flex-col gap-1.5">
            <label className="text-label-small text-muted-foreground">
              End Date
            </label>
            <Input
              type="date"
              value={source.endDate ?? ""}
              onChange={(e) => onChange({ endDate: e.target.value })}
            />
          </div>
        )}
      </div>

      {/* Still in position checkbox */}
      <div className="flex items-center gap-2">
        <Checkbox
          id={`${source.id}-still-in-position`}
          checked={source.stillInPosition ?? true}
          onCheckedChange={(checked) =>
            onChange({ stillInPosition: checked === true })
          }
        />
        <label
          htmlFor={`${source.id}-still-in-position`}
          className="text-body-small cursor-pointer"
        >
          Still in position
        </label>
      </div>

      {/* Company Name */}
      <div className="flex flex-col gap-1.5">
        <label className="text-label-small text-muted-foreground">
          Company Name
        </label>
        <Input
          value={source.companyName ?? ""}
          onChange={(e) => onChange({ companyName: e.target.value })}
          placeholder="e.g. Acme Corporation"
        />
      </div>

      {/* Company Address — autocomplete */}
      <div className="flex flex-col gap-1.5">
        <label className="text-label-small text-muted-foreground">
          Company Address
        </label>
        <AddressAutocomplete
          value={source.companyAddress ?? ""}
          onValueChange={(v) => onChange({ companyAddress: v })}
        />
      </div>

      {/* Income Amount + Frequency — input/slider left, toggle right */}
      <div className="flex flex-col gap-1.5">
        <label className="text-label-small text-muted-foreground">
          Income Amount
        </label>
        <div className="flex items-start gap-3">
          <CurrencyInputWithSlider
            className="flex-1"
            value={source.incomeAmount ?? 0}
            min={0}
            max={50000}
            step={100}
            onValueChange={(v) => onChange({ incomeAmount: v })}
          />
          <LoanOptionGroup
            className="shrink-0"
            options={FREQUENCY_OPTIONS}
            value={source.incomeFrequency ?? ""}
            onChange={(v) => {
              if (typeof v === "string")
                onChange({ incomeFrequency: v as IncomeFrequency });
            }}
          />
        </div>
      </div>

      {/* Type of Company */}
      <div className="flex flex-col gap-2">
        <span className="text-label-small text-muted-foreground">
          Type of Company
        </span>
        <RadioGroup
          value={source.companyType}
          onValueChange={(v) =>
            onChange({ companyType: v as IncomeCompanyType })
          }
          className="flex flex-row gap-4"
        >
          <div className="flex items-center gap-2">
            <RadioGroupItem value="public" id={`${source.id}-public`} />
            <label
              htmlFor={`${source.id}-public`}
              className="text-body-small cursor-pointer"
            >
              Public
            </label>
          </div>
          <div className="flex items-center gap-2">
            <RadioGroupItem value="private" id={`${source.id}-private`} />
            <label
              htmlFor={`${source.id}-private`}
              className="text-body-small cursor-pointer"
            >
              Private
            </label>
          </div>
        </RadioGroup>
      </div>
    </div>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * IncomeWorkDetails — Income section of the loan application wizard.
 *
 * Shows:
 * 1. "{applicantName} Income" heading
 * 2. Open Banking summary card — total, mini bar chart, "Add More Account +"
 * 3. Income Sources — "Total Income" indicator bar
 * 4. Work Details — accordion of employment source forms
 *
 * Figma: WealthX-Backoffice---Mobile-App — node 19308:53126
 */
export function IncomeWorkDetails({
  applicantName,
  totalIncome,
  incomeData,
  sources,
  onSourceChange,
  onAddSource,
  onConnectMore,
  className,
}: IncomeWorkDetailsProps) {
  const [openItems, setOpenItems] = React.useState<string[]>(
    sources.length > 0 ? [sources[0].id] : [],
  );

  // Auto-open any source that was added after initial render
  React.useEffect(() => {
    setOpenItems((current) => {
      const currentSet = new Set(current);
      const newIds = sources
        .map((s) => s.id)
        .filter((id) => !currentSet.has(id));
      return newIds.length > 0 ? [...current, ...newIds] : current;
    });
  }, [sources]);

  return (
    <div className={cn("flex flex-col gap-6 font-sans", className)}>
      {/* Heading */}
      <h2 className="text-h3 text-foreground">{applicantName}&apos;s Income</h2>

      {/* Open Banking summary — left card + right chart */}
      {totalIncome !== undefined && (
        <div className="flex flex-col gap-4 sm:flex-row sm:items-stretch">
          {/* Left: bordered card — amount + button */}
          <Card className="w-full shrink-0 sm:w-[202px]">
            <CardContent className="flex flex-col gap-3 p-4">
              <div className="flex flex-col gap-1 flex-1">
                <span className="text-h2 text-foreground">
                  {formatCurrency(totalIncome)}
                </span>
                <span className="text-body-small text-muted-foreground">
                  Total latest 12 months
                </span>
              </div>
              <Button
                variant="secondary"
                size="sm"
                className="w-fit"
                onClick={onConnectMore}
              >
                Add More Account +
              </Button>
            </CardContent>
          </Card>

          {/* Right: bare bar chart with Y-axis + X-axis */}
          {incomeData && (
            <IncomeBarChart
              incomeData={incomeData}
              showLegend={false}
              showYAxis
              showXAxis
              defaultPeriod={12}
              height={160}
              className="flex-1"
            />
          )}
        </div>
      )}

      {/* Income Sources */}
      <div className="flex flex-col gap-2">
        <h3 className="text-h5 text-foreground">Income Sources</h3>
        <div className="flex flex-col gap-1.5">
          <span className="text-label-small text-muted-foreground">
            Total Income
          </span>
          {/* Full-width indicator bar — green when totalIncome > 0, muted otherwise */}
          <div
            className={cn(
              "h-5 w-full",
              totalIncome ? "bg-primary" : "bg-muted",
            )}
          />
        </div>
      </div>

      {/* Work Details */}
      <div className="flex flex-col gap-3">
        <h3 className="text-h5 text-foreground">Work Details</h3>
        <Accordion
          multiple
          value={openItems}
          onValueChange={setOpenItems}
          className="border-t border-border"
        >
          {sources.map((source) => (
            <AccordionItem key={source.id} value={source.id}>
              <AccordionTrigger>
                {source.label ?? "Main Income Source"}
              </AccordionTrigger>
              <AccordionContent className="text-foreground">
                <IncomeSourceForm
                  source={source}
                  onChange={(updates) => onSourceChange?.(source.id, updates)}
                />
              </AccordionContent>
            </AccordionItem>
          ))}
        </Accordion>

        <Button
          variant="outline"
          size="sm"
          className="w-fit"
          onClick={onAddSource}
        >
          Add More +
        </Button>
      </div>
    </div>
  );
}
