import { useEffect, useState } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { toast } from "sonner";

import { Page } from "@/components/app/Page";
import { PageHeading, SectionHeading } from "@/components/app/Primitives";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useCompanySettings, useUpdateCompanySettings } from "@/features/company-settings/api";
import { ApiClientError } from "@/lib/api";

export const Route = createFileRoute("/settings")({
  head: () => ({
    meta: [
      { title: "Settings | KareVoyage Operations" },
      { name: "description", content: "Organisation details, operational defaults and portal preferences." },
      { property: "og:title", content: "Settings | KareVoyage Operations" },
      { property: "og:description", content: "Configure how the KareVoyage portal behaves." },
    ],
  }),
  component: SettingsPage,
});

const TOGGLES = [
  { label: "Require document verification before departure", hint: "Blocks trip confirmation until every passport is verified." },
  { label: "Auto-remind guests about pending payments", hint: "Sends a reminder 7 days before the due date." },
  { label: "Notify tour managers of itinerary changes", hint: "Push and email on any day-plan edit." },
  { label: "Allow paste-from-Excel imports", hint: "Keeps the bulk import workflow available in every module." },
];

function SettingsPage() {
  const { data: companySettings } = useCompanySettings();
  const updateCompanySettings = useUpdateCompanySettings();
  const [companyName, setCompanyName] = useState("");

  useEffect(() => {
    if (companySettings) setCompanyName(companySettings.companyName);
  }, [companySettings]);

  const handleSave = () => {
    updateCompanySettings.mutate(companyName, {
      onSuccess: () => toast.success("Settings saved."),
      onError: (err) =>
        toast.error(err instanceof ApiClientError ? err.message : "Couldn't save settings."),
    });
  };

  return (
    <Page className="space-y-8">
      <PageHeading
        title="Settings"
        description="Organisation details and the operational defaults every module follows."
        actions={
          <Button onClick={handleSave} disabled={updateCompanySettings.isPending}>
            Save changes
          </Button>
        }
      />

      <section className="grid gap-6 lg:grid-cols-2">
        <div className="rounded-xl border border-border bg-surface p-5">
          <SectionHeading title="Organisation" />
          <div className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="org-name" className="text-xs text-muted-foreground">
                Company name
              </Label>
              <Input
                id="org-name"
                value={companyName}
                onChange={(e) => setCompanyName(e.target.value)}
                className="bg-background"
              />
              <p className="text-xs text-muted-foreground">
                Shown as "Tour Operated By" on every tour.
              </p>
            </div>
            {[
              { id: "org-email", label: "Support email", value: "care@karevoyage.com" },
              { id: "org-phone", label: "Support phone", value: "+91 98200 11223" },
              { id: "org-gst", label: "GSTIN", value: "27AAKCK1234M1Z9" },
            ].map((f) => (
              <div key={f.id} className="space-y-1.5">
                <Label htmlFor={f.id} className="text-xs text-muted-foreground">{f.label}</Label>
                <Input id={f.id} defaultValue={f.value} className="bg-background" />
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-xl border border-border bg-surface p-5">
          <SectionHeading title="Operational defaults" />
          <div className="space-y-4">
            {[
              { id: "currency", label: "Default currency", value: "INR (₹)" },
              { id: "timezone", label: "Time zone", value: "Asia/Kolkata (GMT+5:30)" },
              { id: "date-format", label: "Date format", value: "DD MMM YYYY" },
              { id: "payment-terms", label: "Payment due (days before departure)", value: "30" },
            ].map((f) => (
              <div key={f.id} className="space-y-1.5">
                <Label htmlFor={f.id} className="text-xs text-muted-foreground">{f.label}</Label>
                <Input id={f.id} defaultValue={f.value} className="bg-background" />
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="rounded-xl border border-border bg-surface p-5">
        <SectionHeading title="Automation" description="Guard-rails that keep journeys on track." />
        <ul className="divide-y divide-border">
          {TOGGLES.map((t, i) => (
            <li key={t.label} className="flex items-start justify-between gap-6 py-3.5">
              <div>
                <p className="text-sm font-medium">{t.label}</p>
                <p className="text-xs text-muted-foreground">{t.hint}</p>
              </div>
              <Switch defaultChecked={i !== 3 ? true : true} onCheckedChange={() => toast.success("Preference updated.")} />
            </li>
          ))}
        </ul>
      </section>
    </Page>
  );
}
