"use client";

import { useActionState, useEffect } from "react";
import { toast } from "sonner";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ResponsiveSheet, FormWizard } from "@/components/ui/responsive-sheet";
import { createInvestorAction, updateInvestorAction } from "@/lib/appwrite/investor-actions";
import type { Investor } from "@/lib/appwrite/schema";

type ActionState = { ok: boolean; error?: string; fieldErrors?: Record<string, string[]> };
const INITIAL: ActionState = { ok: false };

interface InvestorFormSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  investor?: Investor | null;
  onSuccess?: () => void;
}

export function InvestorFormSheet({ open, onOpenChange, investor, onSuccess }: InvestorFormSheetProps) {
  const action = investor ? updateInvestorAction.bind(null, investor.$id) : createInvestorAction;
  const [state, formAction, isPending] = useActionState(action, INITIAL);

  useEffect(() => {
    if (state.ok) {
      toast.success(investor ? "Yatırımcı güncellendi." : "Yatırımcı oluşturuldu.");
      onSuccess?.();
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  const fe = state.fieldErrors ?? {};

  const steps = [
    {
      label: "Kişi",
      content: (
        <>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1.5">
              <Label htmlFor="name">Ad Soyad *</Label>
              <Input id="name" name="name" defaultValue={investor?.name} placeholder="Mehmet Demir" />
              {fe.name && <p className="text-destructive text-xs">{fe.name[0]}</p>}
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="phone">Telefon</Label>
              <Input id="phone" name="phone" type="tel" defaultValue={investor?.phone ?? ""} placeholder="+90 555 123 45 67" />
            </div>
          </div>
          <div className="grid gap-1.5">
            <Label htmlFor="email">Email *</Label>
            <Input id="email" name="email" type="email" defaultValue={investor?.email} placeholder="mehmet@example.com" />
            {fe.email && <p className="text-destructive text-xs">{fe.email[0]}</p>}
          </div>
        </>
      ),
    },
    {
      label: "Finansal",
      content: (
        <div className="grid grid-cols-3 gap-3">
          <div className="col-span-2 grid gap-1.5">
            <Label htmlFor="budget">Bütçe</Label>
            <Input id="budget" name="budget" type="number" min="0"
              defaultValue={investor?.budget ?? ""} placeholder="5.000.000" />
          </div>
          <div className="grid gap-1.5">
            <Label>Para birimi</Label>
            <select name="currency" defaultValue={investor?.currency ?? "TRY"}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm">
              <option value="TRY">TRY</option>
              <option value="USD">USD</option>
              <option value="EUR">EUR</option>
            </select>
          </div>
        </div>
      ),
    },
    {
      label: "Not",
      content: (
        <div className="grid gap-1.5">
          <Label htmlFor="notes">Notlar</Label>
          <Textarea id="notes" name="notes" rows={5} defaultValue={investor?.notes ?? ""} placeholder="Yatırım tercihleri..." />
        </div>
      ),
    },
  ];

  return (
    <ResponsiveSheet open={open} onOpenChange={onOpenChange}
      title={investor ? "Yatırımcıyı Düzenle" : "Yeni Yatırımcı"}
      maxWidth="sm:max-w-lg">
      <form
        action={formAction}
        onKeyDown={(e) => {
          if (e.key === "Enter" && (e.target as HTMLElement).tagName !== "TEXTAREA") {
            e.preventDefault();
          }
        }}
      >
        <FormWizard steps={steps} isPending={isPending} submitLabel={investor ? "Güncelle" : "Oluştur"} />
      </form>
    </ResponsiveSheet>
  );
}
