/**
 * Shipment Tracking General Tab
 */

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"
import { usePro } from "@/contexts/pro-context"
import { cn } from "@/lib/utils"
import { TrackingSettings, Carrier } from "../../types"
import { Check, ChevronsUpDown, Settings, Truck, X } from "lucide-react"

interface GeneralTabProps {
  settings: TrackingSettings
  carriers: Record<string, Carrier>
  updateSetting: <K extends keyof TrackingSettings>(key: K, value: TrackingSettings[K]) => void
}

export function GeneralTab({ settings, carriers, updateSetting }: GeneralTabProps) {
  const { isPro } = usePro()
  const carrierList = Object.entries(carriers)
  const [importFile, setImportFile] = useState<File | null>(null)
  const [isImporting, setIsImporting] = useState(false)
  const [defaultCarrierOpen, setDefaultCarrierOpen] = useState(false)
  const [carrierPickerOpen, setCarrierPickerOpen] = useState(false)
  const enabledCarriers = settings.enabled_carriers || []
  const defaultCarrierName = carriers[settings.default_carrier]?.name || 'Select default carrier'
  const selectedCarrierNames = enabledCarriers
    .map((id) => carriers[id]?.name)
    .filter(Boolean)
  
  const toggleCarrier = (carrierId: string) => {
    if (enabledCarriers.includes(carrierId)) {
      updateSetting('enabled_carriers', enabledCarriers.filter(id => id !== carrierId))
    } else {
      updateSetting('enabled_carriers', [...enabledCarriers, carrierId])
    }
  }

  const selectDefaultCarrier = (carrierId: string) => {
    updateSetting('default_carrier', carrierId)
    setDefaultCarrierOpen(false)
  }

  const handleCsvImport = async () => {
    if (!importFile) return

    const apiUrl = (window as any).swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
    const nonce = (window as any).swiftCommerceData?.restNonce || ''
    const formData = new FormData()
    formData.append('file', importFile)

    setIsImporting(true)
    try {
      const response = await fetch(`${apiUrl}/shipment-tracking/import`, {
        method: 'POST',
        headers: {
          'X-WP-Nonce': nonce,
        },
        body: formData,
      })

      const result = await response.json()
      if (!response.ok) {
        throw new Error(result?.message || 'Import failed')
      }

      alert(`Imported ${result.imported || 0} tracking rows. Skipped ${result.skipped || 0}.`)
      setImportFile(null)
    } catch (error) {
      alert(error instanceof Error ? error.message : 'Import failed')
    } finally {
      setIsImporting(false)
    }
  }

  return (
    <div className="grid gap-6 md:grid-cols-2">
      {/* General Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="h-5 w-5" />
            General Settings
          </CardTitle>
          <CardDescription>
            Configure basic shipment tracking options
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="default_carrier">Default Carrier</Label>
            <Popover open={defaultCarrierOpen} onOpenChange={setDefaultCarrierOpen}>
              <PopoverTrigger asChild>
                <Button
                  id="default_carrier"
                  variant="outline"
                  role="combobox"
                  aria-expanded={defaultCarrierOpen}
                  className="w-full justify-between"
                >
                  <span className="truncate">{defaultCarrierName}</span>
                  <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
                <Command>
                  <CommandInput placeholder="Search carriers..." />
                  <CommandList>
                    <CommandEmpty>No carrier found.</CommandEmpty>
                    <CommandGroup>
                      {carrierList.map(([id, carrier]) => (
                        <CommandItem
                          key={id}
                          value={`${carrier.name} ${id}`}
                          onSelect={() => selectDefaultCarrier(id)}
                        >
                          <Check
                            className={cn(
                              "mr-2 h-4 w-4",
                              settings.default_carrier === id ? "opacity-100" : "opacity-0"
                            )}
                          />
                          {carrier.name}
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
            <p className="text-sm text-muted-foreground">
              Pre-selected carrier when adding tracking
            </p>
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label htmlFor="auto_complete">Auto-Complete Orders</Label>
              <p className="text-sm text-muted-foreground">
                Mark orders as completed when tracking is added
              </p>
            </div>
            <Switch
              id="auto_complete"
              checked={settings.auto_complete_order}
              onCheckedChange={(checked) => updateSetting('auto_complete_order', checked)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Display Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Truck className="h-5 w-5" />
            Display Settings
          </CardTitle>
          <CardDescription>
            Configure where tracking information appears
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label htmlFor="show_in_email">Show in Order Emails</Label>
              <p className="text-sm text-muted-foreground">
                Include tracking info in order completion emails
              </p>
            </div>
            <Switch
              id="show_in_email"
              checked={settings.show_in_order_email}
              onCheckedChange={(checked) => updateSetting('show_in_order_email', checked)}
            />
          </div>

          {settings.show_in_order_email && (
            <div className="space-y-2">
              <Label htmlFor="email_position">Email Placement</Label>
              <Select
                value={settings.email_position || 'before_order_table'}
                onValueChange={(value) => updateSetting('email_position', value as TrackingSettings['email_position'])}
              >
                <SelectTrigger id="email_position">
                  <SelectValue placeholder="Select placement" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="before_order_table">Before order table</SelectItem>
                  <SelectItem value="after_order_table">After order table</SelectItem>
                </SelectContent>
              </Select>
            </div>
          )}

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label htmlFor="show_in_account">Show in My Account</Label>
              <p className="text-sm text-muted-foreground">
                Display tracking in customer's order view
              </p>
            </div>
            <Switch
              id="show_in_account"
              checked={settings.show_in_my_account}
              onCheckedChange={(checked) => updateSetting('show_in_my_account', checked)}
            />
          </div>

          {settings.show_in_my_account && (
            <div className="space-y-2">
              <Label htmlFor="order_details_position">My Account Placement</Label>
              <Select
                value={settings.order_details_position || 'after_order_table'}
                onValueChange={(value) => updateSetting('order_details_position', value as TrackingSettings['order_details_position'])}
              >
                <SelectTrigger id="order_details_position">
                  <SelectValue placeholder="Select placement" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="before_order_table">Before order table</SelectItem>
                  <SelectItem value="after_order_table">After order table</SelectItem>
                </SelectContent>
              </Select>
            </div>
          )}

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label htmlFor="show_in_orders_list">Show in Orders Lists</Label>
              <p className="text-sm text-muted-foreground">
                Add tracking summaries to admin orders and customer order lists
              </p>
            </div>
            <Switch
              id="show_in_orders_list"
              checked={settings.show_in_orders_list}
              onCheckedChange={(checked) => updateSetting('show_in_orders_list', checked)}
            />
          </div>

        </CardContent>
      </Card>

      <div className="grid gap-6 md:col-span-2 lg:grid-cols-2">
      {/* Shipping Carriers */}
      <Card>
        <CardHeader>
          <CardTitle>Shipping Carriers</CardTitle>
          <CardDescription>
            Search and select carriers available when adding tracking.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <Popover open={carrierPickerOpen} onOpenChange={setCarrierPickerOpen}>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                role="combobox"
                aria-expanded={carrierPickerOpen}
                className="w-full justify-between"
              >
                <span className="truncate">
                  {enabledCarriers.length > 0
                    ? `${enabledCarriers.length} carriers enabled`
                    : 'Select carriers'}
                </span>
                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
              <Command>
                <CommandInput placeholder="Search carriers..." />
                <CommandList>
                  <CommandEmpty>No carrier found.</CommandEmpty>
                  <CommandGroup>
                    {carrierList.map(([id, carrier]) => {
                      const isEnabled = enabledCarriers.includes(id)
                      return (
                        <CommandItem
                          key={id}
                          value={`${carrier.name} ${id}`}
                          onSelect={() => toggleCarrier(id)}
                        >
                          <Check
                            className={cn(
                              "mr-2 h-4 w-4",
                              isEnabled ? "opacity-100" : "opacity-0"
                            )}
                          />
                          {carrier.name}
                        </CommandItem>
                      )
                    })}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>

          {selectedCarrierNames.length > 0 ? (
            <div className="flex flex-wrap gap-2">
              {enabledCarriers.map((id) => {
                const carrier = carriers[id]
                if (!carrier) return null

                return (
                  <Badge key={id} variant="secondary" className="gap-1">
                    {carrier.name}
                    <button
                      type="button"
                      onClick={() => toggleCarrier(id)}
                      className="rounded-full p-0.5 hover:bg-muted-foreground/20"
                      aria-label={`Remove ${carrier.name}`}
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </Badge>
                )
              })}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">
              No carriers enabled yet.
            </p>
          )}
        </CardContent>
      </Card>

      {/* CSV Import */}
      {isPro && (
      <Card>
        <CardHeader>
          <CardTitle>CSV Import</CardTitle>
          <CardDescription>
            Bulk add tracking details to existing WooCommerce orders.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
            <Input
              type="file"
              accept=".csv,text/csv"
              onChange={(event) => setImportFile(event.target.files?.[0] || null)}
            />
            <Button
              type="button"
              onClick={handleCsvImport}
              disabled={!importFile || isImporting}
            >
              {isImporting ? 'Importing...' : 'Import CSV'}
            </Button>
          </div>
          <p className="text-sm text-muted-foreground">
            Required headers: <code className="bg-muted px-1 rounded">order_id</code>, <code className="bg-muted px-1 rounded">tracking_number</code>. Optional: <code className="bg-muted px-1 rounded">carrier</code>, <code className="bg-muted px-1 rounded">date_shipped</code>, <code className="bg-muted px-1 rounded">estimated_delivery_date</code>, <code className="bg-muted px-1 rounded">custom_url</code>, <code className="bg-muted px-1 rounded">send_notification</code>.
          </p>
        </CardContent>
      </Card>
      )}
      </div>
    </div>
  )
}
