"use client";

import { useState } from "react";
import { Loader2, Plus, Trash2 } from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useT } from "@/shared/i18n/client";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Textarea } from "@/presentation/components/ui/textarea";
import { Label } from "@/presentation/components/ui/label";
import { Switch } from "@/presentation/components/ui/switch";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/presentation/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/presentation/components/ui/select";
import type { AdminStoreModule, UpdateStoreModulePayload } from "@/domain/entities/store";

/** A Store module's catalogue entry: texts, monthly price, publication and order. */
export function StoreModuleDialog({ module, onOpenChange, onSaved }: {
  module: AdminStoreModule | null;
  onOpenChange: (open: boolean) => void;
  onSaved: () => void;
}) {
  const t = useT();

  return (
    <Dialog open={!!module} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{module ? t.store.editTitle(module.name) : ""}</DialogTitle>
          <DialogDescription>{module?.key}</DialogDescription>
        </DialogHeader>
        {module && <StoreModuleForm key={module.key} module={module} onClose={() => onOpenChange(false)} onSaved={onSaved} />}
      </DialogContent>
    </Dialog>
  );
}

function StoreModuleForm({ module, onClose, onSaved }: {
  module: AdminStoreModule;
  onClose: () => void;
  onSaved: () => void;
}) {
  const t = useT();
  const container = useRepositories();
  const [draft, setDraft] = useState({
    name: module.name,
    tagline: module.tagline ?? "",
    problem: module.problem ?? "",
    solution: module.solution ?? "",
    gains: module.gains ?? [],
    needs: module.needs ?? "",
    category: module.category ?? "",
    price_ht: String(module.price_ht ?? 0),
    published: module.published,
    position: String(module.position ?? 0),
  });
  const set = <K extends keyof typeof draft>(k: K, v: (typeof draft)[K]) => setDraft((d) => ({ ...d, [k]: v }));

  const save = useApiMutation(
    (payload: UpdateStoreModulePayload) => container.storeRepository.updateModule(module.key, payload),
    { successMessage: t.store.saved, onSuccess: onSaved }
  );

  const submit = () => {
    save.mutate({
      name: draft.name.trim(),
      tagline: draft.tagline.trim(),
      problem: draft.problem.trim(),
      solution: draft.solution.trim(),
      gains: draft.gains.map((g) => g.trim()).filter(Boolean),
      needs: draft.needs.trim() || null,
      category: draft.category,
      price_ht: Number(draft.price_ht) || 0,
      published: draft.published,
      position: parseInt(draft.position, 10) || 0,
    });
  };

  const categories = t.store.categories.includes(draft.category) || !draft.category
    ? t.store.categories
    : [...t.store.categories, draft.category];

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <Field label={t.store.fields.name}>
          <Input value={draft.name} onChange={(e) => set("name", e.target.value)} />
        </Field>
        <Field label={t.store.fields.category}>
          <Select value={draft.category} onValueChange={(v) => set("category", v)}>
            <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
            <SelectContent>
              {categories.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}
            </SelectContent>
          </Select>
        </Field>
      </div>
      <Field label={t.store.fields.tagline}>
        <Input value={draft.tagline} onChange={(e) => set("tagline", e.target.value)} />
      </Field>
      <Field label={t.store.fields.problem}>
        <Textarea rows={3} value={draft.problem} onChange={(e) => set("problem", e.target.value)} />
      </Field>
      <Field label={t.store.fields.solution}>
        <Textarea rows={3} value={draft.solution} onChange={(e) => set("solution", e.target.value)} />
      </Field>
      <StringListField label={t.store.fields.gains} values={draft.gains} onChange={(v) => set("gains", v)} />
      <Field label={t.store.fields.needs}>
        <Input value={draft.needs} onChange={(e) => set("needs", e.target.value)} />
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label={t.store.fields.price}>
          <Input type="number" min={0} step="0.01" value={draft.price_ht} onChange={(e) => set("price_ht", e.target.value)} />
        </Field>
        <Field label={t.store.fields.position}>
          <Input type="number" min={0} step={1} value={draft.position} onChange={(e) => set("position", e.target.value)} />
        </Field>
      </div>
      <div className="flex items-center gap-2">
        <Switch id="store-published" checked={draft.published} onCheckedChange={(v) => set("published", v)} />
        <Label htmlFor="store-published">{t.store.fields.published}</Label>
      </div>
      <div className="flex justify-end gap-2 pt-2">
        <Button variant="outline" onClick={onClose}>{t.store.cancel}</Button>
        <Button onClick={submit} disabled={save.loading || !draft.name.trim()}>
          {save.loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
          {t.store.save}
        </Button>
      </div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="space-y-1.5">
      <Label>{label}</Label>
      {children}
    </div>
  );
}

function StringListField({ label, values, onChange }: { label: string; values: string[]; onChange: (values: string[]) => void }) {
  const t = useT();
  return (
    <div className="space-y-1.5">
      <Label>{label}</Label>
      {values.map((v, i) => (
        <div key={i} className="flex gap-2">
          <Input value={v} onChange={(e) => onChange(values.map((x, j) => (j === i ? e.target.value : x)))} />
          <Button variant="ghost" size="icon" title={t.store.removeLine} onClick={() => onChange(values.filter((_, j) => j !== i))}>
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      ))}
      <Button variant="outline" size="sm" onClick={() => onChange([...values, ""])}>
        <Plus className="w-3 h-3 mr-2" />
        {t.store.addLine}
      </Button>
    </div>
  );
}
