import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Checkbox } from "@/components/ui/checkbox"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { wordpressRoles } from "@/features/spam/email-verification/config"
import { AbandonedCartSettings } from "../../types"

interface AdvancedTabProps {
  settings: AbandonedCartSettings
  updateSettings: (updates: Partial<AbandonedCartSettings>) => void
}

const ORDER_STATUSES = [
  { value: "pending", label: "Pending Payment" },
  { value: "failed", label: "Failed" },
  { value: "on-hold", label: "On Hold" },
] as const

export function AdvancedTab({ settings, updateSettings }: AdvancedTabProps) {
  const toggleOrderStatus = (status: string) => {
    const current = settings.unpaidOrderStatuses || []
    updateSettings({
      unpaidOrderStatuses: current.includes(status)
        ? current.filter((item) => item !== status)
        : [...current, status],
    })
  }

  const toggleExcludeRole = (role: string) => {
    const current = settings.excludeRoles || []
    updateSettings({
      excludeRoles: current.includes(role)
        ? current.filter((item) => item !== role)
        : [...current, role],
    })
  }

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Unpaid Order Recovery</CardTitle>
            <CardDescription>Send payment reminders for pending, failed, or on-hold orders.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between gap-6">
              <Label htmlFor="recoverUnpaidOrders">Enable Unpaid Order Recovery</Label>
              <Switch
                id="recoverUnpaidOrders"
                checked={settings.recoverUnpaidOrders}
                onCheckedChange={(checked) => updateSettings({ recoverUnpaidOrders: checked })}
              />
            </div>

            {settings.recoverUnpaidOrders && (
              <>
                <div className="grid gap-2">
                  <Label htmlFor="unpaidOrderThreshold">Payment Timeout (minutes)</Label>
                  <Input
                    id="unpaidOrderThreshold"
                    type="number"
                    min={15}
                    max={10080}
                    value={settings.unpaidOrderThreshold}
                    onChange={(event) => updateSettings({ unpaidOrderThreshold: parseInt(event.target.value) || 60 })}
                  />
                </div>
                <div className="grid gap-3">
                  <Label>Order Statuses to Track</Label>
                  {ORDER_STATUSES.map((status) => (
                    <div key={status.value} className="flex items-center gap-2">
                      <Checkbox
                        id={`status-${status.value}`}
                        checked={(settings.unpaidOrderStatuses || []).includes(status.value)}
                        onCheckedChange={() => toggleOrderStatus(status.value)}
                      />
                      <Label htmlFor={`status-${status.value}`} className="cursor-pointer font-normal">
                        {status.label}
                      </Label>
                    </div>
                  ))}
                </div>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Admin Recovery Notification</CardTitle>
            <CardDescription>Notify the store team after a paid cart or unpaid order is recovered.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between gap-6">
              <Label htmlFor="adminNotifyOnRecovery">Enable Admin Notification</Label>
              <Switch
                id="adminNotifyOnRecovery"
                checked={settings.adminNotifyOnRecovery}
                onCheckedChange={(checked) => updateSettings({ adminNotifyOnRecovery: checked })}
              />
            </div>
            {settings.adminNotifyOnRecovery && (
              <div className="grid gap-2">
                <Label htmlFor="adminNotifyEmail">Notification Email</Label>
                <Input
                  id="adminNotifyEmail"
                  type="email"
                  value={settings.adminNotifyEmail}
                  onChange={(event) => updateSettings({ adminNotifyEmail: event.target.value })}
                  placeholder="Defaults to the WordPress admin email"
                />
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Exclude Roles from Tracking</CardTitle>
          <CardDescription>Exclude staff or other internal roles from recovery tracking.</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {wordpressRoles.map((role) => (
            <div key={role.value} className="flex items-center gap-2">
              <Checkbox
                id={`exclude-role-${role.value}`}
                checked={(settings.excludeRoles || []).includes(role.value)}
                onCheckedChange={() => toggleExcludeRole(role.value)}
              />
              <Label htmlFor={`exclude-role-${role.value}`} className="cursor-pointer font-normal">
                {role.label}
              </Label>
            </div>
          ))}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Recovery Eligibility</CardTitle>
            <CardDescription>Only retain carts that meet your minimum value.</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-2">
            <Label htmlFor="minCartValue">Minimum Cart Value</Label>
            <Input
              id="minCartValue"
              type="number"
              min={0}
              step="0.01"
              value={settings.minCartValue || 0}
              onChange={(event) => updateSettings({ minCartValue: Math.max(0, parseFloat(event.target.value) || 0) })}
            />
            <p className="text-sm text-muted-foreground">Uses the store currency. Set to 0 to track every cart.</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Abandonment Webhook</CardTitle>
            <CardDescription>Notify an endpoint when an eligible cart becomes abandoned.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-2">
              <Label htmlFor="webhookUrl">Webhook URL</Label>
              <Input
                id="webhookUrl"
                type="url"
                value={settings.webhookUrl || ""}
                onChange={(event) => updateSettings({ webhookUrl: event.target.value })}
                placeholder="https://automation.example.com/hooks/cart"
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="webhookSecret">Signing Secret</Label>
              <Input
                id="webhookSecret"
                type="password"
                autoComplete="new-password"
                value={settings.webhookSecret || ""}
                onChange={(event) => updateSettings({ webhookSecret: event.target.value })}
                placeholder="Optional shared secret"
              />
              <p className="text-sm text-muted-foreground">
                Requests include the customer email, total, currency, and an HMAC signature when configured.
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
