"use client";

import { useState } from "react";
import { Truck, Plus } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { SettingsCard } from "./settings-card";
import { SettingField } from "./setting-field";
import { SaveButton } from "./save-button";
import {
  updateShippingSettings,
  type StoreSettingsData,
  type ShippingMethodInput,
} from "@/lib/actions/settings";

interface ShippingSettingsProps {
  settings: StoreSettingsData;
}

/**
 * Shipping zones/methods, their rates, and the free-shipping threshold.
 */
export function ShippingSettings({ settings }: ShippingSettingsProps) {
  const [methods, setMethods] = useState<ShippingMethodInput[]>(
    settings.shippingMethods,
  );
  const [freeShipping, setFreeShipping] = useState(
    settings.freeShippingEnabled,
  );
  const [threshold, setThreshold] = useState(
    String(settings.freeShippingThreshold || 2000),
  );

  const updateMethod = (id: string, patch: Partial<ShippingMethodInput>) => {
    setMethods((prev) =>
      prev.map((m) => (m.id === id ? { ...m, ...patch } : m)),
    );
  };

  return (
    <SettingsCard
      title="Shipping"
      description="Configure delivery methods, rates, and free-shipping rules."
      icon={<Truck className="h-4 w-4" />}
      footer={
        <SaveButton
          onSave={() =>
            updateShippingSettings({
              methods,
              freeShippingEnabled: freeShipping,
              freeShippingThreshold: Number(threshold) || 0,
            })
          }
        />
      }
    >
      <div className="space-y-6">
        {/* Methods */}
        <div className="space-y-1">
          <p className="text-sm font-medium">Shipping methods</p>
          <p className="text-xs text-muted-foreground">
            Turn a method off to hide it at checkout.
          </p>
        </div>
        <ul className="-mt-2 space-y-3">
          {methods.map((method) => (
            <li
              key={method.id}
              className="flex flex-col gap-3 rounded-lg border bg-muted/20 p-4 sm:flex-row sm:items-center sm:gap-4"
            >
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <Switch
                    checked={method.enabled}
                    onCheckedChange={(v) =>
                      updateMethod(method.id, { enabled: v })
                    }
                    aria-label={`Enable ${method.name}`}
                  />
                  <span
                    className={
                      method.enabled
                        ? "text-sm font-medium"
                        : "text-sm font-medium text-muted-foreground line-through"
                    }
                  >
                    {method.name}
                  </span>
                </div>
                <p className="mt-1 pl-9 text-xs text-muted-foreground">
                  {method.description}
                </p>
              </div>
              <div className="flex items-center gap-2 pl-9 sm:pl-0">
                <span className="text-sm text-muted-foreground">৳</span>
                <Input
                  value={method.rate}
                  onChange={(e) =>
                    updateMethod(method.id, { rate: e.target.value })
                  }
                  inputMode="numeric"
                  className="h-8 w-24 text-right font-mono"
                  aria-label={`Rate for ${method.name}`}
                />
              </div>
            </li>
          ))}
        </ul>

        <Button variant="ghost" size="sm">
          <Plus className="h-4 w-4 mr-1.5" />
          Add shipping method
        </Button>

        <Separatorish />

        {/* Free shipping */}
        <SettingField
          id="free-shipping"
          label="Free shipping"
          description="Automatically waive the delivery fee on qualifying orders."
          controlClassName="sm:w-auto sm:shrink-0"
          control={
            <Switch
              id="free-shipping"
              checked={freeShipping}
              onCheckedChange={setFreeShipping}
            />
          }
        />

        {freeShipping && (
          <SettingField
            id="free-shipping-threshold"
            label="Free shipping threshold"
            description="Orders at or above this amount ship free."
            control={
              <div className="relative">
                <span className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm text-muted-foreground">
                  ৳
                </span>
                <Input
                  id="free-shipping-threshold"
                  value={threshold}
                  onChange={(e) => setThreshold(e.target.value)}
                  inputMode="numeric"
                  className="pl-7 font-mono"
                />
              </div>
            }
          />
        )}
      </div>
    </SettingsCard>
  );
}

function Separatorish() {
  return <div className="h-px w-full bg-border/60" aria-hidden />;
}