"use client";
import { useState } from "react";
import { useSearchParams } from "next/navigation";
import {
  PageHeader,
  Panel,
  PreviewNotice,
  Metric,
} from "@/components/shared/page";
import { DataTable } from "@/components/shared/data-table";
import { Field, SelectField } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import { ChartPanel } from "@/components/shared/chart";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { usePreviewRole } from "@/components/layout/preview-context";
import { useQueryUpdate } from "@/components/shared/tabs";
import { canManage } from "@/lib/preview";
import { currency } from "@/lib/format";
import { locations } from "@/features/locations/fixtures";
import { scopedLocations } from "@/features/locations/model";
import { roiPeriods } from "./fixtures";
import { summarizeRoi, roiTrend, type Investment } from "./model";
import { useInvestments } from "./store";
export function RoiDashboard() {
  const role = usePreviewRole(),
    params = useSearchParams(),
    update = useQueryUpdate();
  const { investments: items, save, remove } = useInvestments();
  const [selection, setSelection] = useState(""),
    [expanded, setExpanded] = useState(""),
    [draft, setDraft] = useState<Investment | null>(null),
    [deleting, setDeleting] = useState<Investment | null>(null),
    [notice, setNotice] = useState("");
  const allowed = scopedLocations(locations, role),
    locationId = params.get("location_id") ?? "";
  const start = params.get("start_date") ?? "2026-04-01",
    end = params.get("end_date") ?? "2026-10-31",
    period =
      params.get("period") === "quarterly"
        ? "quarterly"
        : params.get("period") === "yearly"
          ? "yearly"
          : "monthly";
  const visible = allowed.filter((row) => !locationId || row.id === locationId),
    rows = visible.map((location) => ({
      id: location.id,
      name: location.name,
      ...summarizeRoi(roiPeriods, items, location.id, start, end),
    }));
  const chartRows = rows.filter((row) => !selection || row.id === selection);
  const total = rows.reduce(
    (sum, row) => ({
      revenue: sum.revenue + row.revenue,
      cost: sum.cost + row.cost,
      investment: sum.investment + row.investment,
      profit: sum.profit + row.profit,
    }),
    { revenue: 0, cost: 0, investment: 0, profit: 0 },
  );
  return (
    <div className="space-y-5">
      <PageHeader title="Return on Investment" />
      {notice && <PreviewNotice>{notice}</PreviewNotice>}
      <Panel
        title="ROI Summary"
        description="Revenue, investment cost, and accumulated profit by location."
      >
        <form
          className="grid items-end gap-4 p-5 sm:grid-cols-3 xl:grid-cols-5"
          onSubmit={(event) => {
            event.preventDefault();
            const data = new FormData(event.currentTarget);
            update({
              start_date: String(data.get("start_date")),
              end_date: String(data.get("end_date")),
            });
          }}
        >
          <SelectField
            label="Location"
            value={locationId}
            options={[
              { value: "", label: "All Assigned Locations" },
              ...allowed.map((row) => ({ value: row.id, label: row.name })),
            ]}
            onChange={(event) => {
              update({ location_id: event.target.value });
              setSelection("");
            }}
          />
          <SelectField
            label="Period"
            value={period}
            options={[
              { value: "monthly", label: "Monthly" },
              { value: "quarterly", label: "Quarterly" },
              { value: "yearly", label: "Yearly" },
            ]}
            onChange={(event) => update({ period: event.target.value })}
          />
          <Field
            label="Start Date"
            name="start_date"
            type="date"
            required
            defaultValue={start}
            max={end}
          />
          <Field
            label="End Date"
            name="end_date"
            type="date"
            required
            defaultValue={end}
            min={start}
          />
          <Button>Apply Filters</Button>
        </form>
      </Panel>
      <div className="grid gap-4 sm:grid-cols-3">
        <Metric label="Total Revenue" value={currency(total.revenue)} />
        <Metric label="Investment Cost" value={currency(total.investment)} />
        <Metric label="Total Profit" value={currency(total.profit)} />
      </div>
      <ChartPanel
        title={
          selection
            ? `${rows.find((row) => row.id === selection)?.name} · ROI Trend`
            : "ROI Trend"
        }
        type="line"
        categories={
          chartRows[0]
            ? roiTrend(
                roiPeriods,
                items,
                chartRows[0].id,
                start,
                end,
                period,
              ).map((point) => point.label)
            : []
        }
        series={chartRows.map((row) => ({
          name: row.name,
          data: roiTrend(roiPeriods, items, row.id, start, end, period).map(
            (point) => point.roi,
          ),
        }))}
      />
      {selection && (
        <Button variant="outline" size="sm" onClick={() => setSelection("")}>
          Clear Location Selection
        </Button>
      )}
      <p className="text-sm text-muted-foreground">
        Click View to see the ROI breakdown for each location.
      </p>
      <DataTable
        title="ROI Breakdown"
        rows={rows}
        columns={[
          { key: "name", label: "Location" },
          {
            key: "revenue",
            label: "Revenue",
            render: (row) => currency(row.revenue),
          },
          { key: "cost", label: "Cost", render: (row) => currency(row.cost) },
          {
            key: "profit",
            label: "Profit",
            render: (row) => currency(row.profit),
          },
          {
            key: "roi",
            label: "ROI Trend",
            render: (row) => (
              <span className="font-medium text-success">
                ↗ {row.roi.toFixed(2)}%
              </span>
            ),
          },
        ]}
        actions={(row) => (
          <>
            <Button
              size="sm"
              variant="outline"
              onClick={() => setSelection(row.id)}
            >
              View
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => setExpanded(expanded === row.id ? "" : row.id)}
            >
              {expanded === row.id ? "Hide" : "Investments"}
            </Button>
            {canManage(role) && (
              <Button
                size="sm"
                onClick={() =>
                  setDraft({
                    id: "",
                    locationId: row.id,
                    name: "",
                    category: "Equipment",
                    quantity: 1,
                    unitCost: 0,
                    date: "2026-10-15",
                    depreciation: 60,
                  })
                }
              >
                Add Investment
              </Button>
            )}
          </>
        )}
      />
      {expanded && allowed.some((row) => row.id === expanded) && (
        <Panel
          title={`Investment Items · ${allowed.find((row) => row.id === expanded)?.name}`}
        >
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Item</th>
                  <th>Category</th>
                  <th>Quantity</th>
                  <th>Unit Cost</th>
                  <th>Total</th>
                  <th>Purchase Date</th>
                  <th>Depreciation</th>
                  {canManage(role) && <th>Actions</th>}
                </tr>
              </thead>
              <tbody>
                {items
                  .filter((row) => row.locationId === expanded)
                  .map((row) => (
                    <tr key={row.id}>
                      <td>{row.name}</td>
                      <td>{row.category}</td>
                      <td>{row.quantity}</td>
                      <td>{currency(row.unitCost)}</td>
                      <td>{currency(row.unitCost * row.quantity)}</td>
                      <td>{row.date}</td>
                      <td>{row.depreciation} months</td>
                      {canManage(role) && (
                        <td>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setDraft({ ...row })}
                          >
                            Edit
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setDeleting(row)}
                          >
                            Delete
                          </Button>
                        </td>
                      )}
                    </tr>
                  ))}
                {!items.some((row) => row.locationId === expanded) && (
                  <tr>
                    <td
                      colSpan={8}
                      className="py-8 text-center text-muted-foreground"
                    >
                      No investments at this location.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </Panel>
      )}
      <Dialog
        open={!!draft}
        onOpenChange={(open) => {
          if (!open) setDraft(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{draft?.id ? "Edit" : "Add"} Investment</DialogTitle>
            <DialogDescription>
              Investment item for{" "}
              {locations.find((row) => row.id === draft?.locationId)?.name}.
              Changes update ROI locally.
            </DialogDescription>
          </DialogHeader>
          {draft && (
            <form
              onSubmit={(event) => {
                event.preventDefault();
                const next = { ...draft, id: draft.id || crypto.randomUUID() };
                save(next);
                setExpanded(next.locationId);
                setNotice("Investment saved in the local ROI preview.");
                setDraft(null);
              }}
            >
              <div className="grid gap-4 sm:grid-cols-2">
                <Field
                  label="Item Name"
                  required
                  value={draft.name}
                  onChange={(event) =>
                    setDraft({ ...draft, name: event.target.value })
                  }
                />
                <SelectField
                  label="Category"
                  value={draft.category}
                  options={[
                    "Equipment",
                    "Installation",
                    "Maintenance",
                    "Other",
                  ]}
                  onChange={(event) =>
                    setDraft({ ...draft, category: event.target.value })
                  }
                />
                <Field
                  label="Quantity"
                  type="number"
                  required
                  min={1}
                  step={1}
                  value={draft.quantity}
                  onChange={(event) =>
                    setDraft({ ...draft, quantity: Number(event.target.value) })
                  }
                />
                <Field
                  label="Unit Cost (IDR)"
                  type="number"
                  required
                  min={0}
                  step="0.01"
                  value={draft.unitCost}
                  onChange={(event) =>
                    setDraft({ ...draft, unitCost: Number(event.target.value) })
                  }
                />
                <Field
                  label="Purchase Date"
                  type="date"
                  required
                  value={draft.date}
                  onChange={(event) =>
                    setDraft({ ...draft, date: event.target.value })
                  }
                />
                <Field
                  label="Depreciation (Months)"
                  type="number"
                  required
                  min={1}
                  step={1}
                  value={draft.depreciation}
                  onChange={(event) =>
                    setDraft({
                      ...draft,
                      depreciation: Number(event.target.value),
                    })
                  }
                />
              </div>
              <DialogFooter className="mt-6">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setDraft(null)}
                >
                  Cancel
                </Button>
                <Button>Save Investment Preview</Button>
              </DialogFooter>
            </form>
          )}
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!deleting}
        onOpenChange={(open) => {
          if (!open) setDeleting(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Investment</DialogTitle>
            <DialogDescription>
              Remove {deleting?.name} from the local ROI calculation?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleting(null)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => {
                if (deleting) remove(deleting.id);
                setNotice("Investment deleted from the local preview.");
                setDeleting(null);
              }}
            >
              Delete Preview
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
