import React, { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';

import {
  getCategories,
  createCampaign,
} from '../service/campaigns/campaigns.service';
import type {
  ICreateCampaignPayload,
  ICampaignDiscountCode,
} from '../service/campaigns/campaigns.interface';

const PRIORITY_OPTIONS = [
  { label: 'Soft - recommend when relevant', value: 'soft' },
  { label: 'Balanced - prefer campaign products', value: 'balanced' },
  { label: 'Strong - only campaign products', value: 'strong' },
];

const GOAL_OPTIONS = [
  { label: 'Conversion - drive purchases', value: 'conversion' },
  { label: 'Awareness - showcase products', value: 'awareness' },
  { label: 'Upsell - upgrade existing interest', value: 'upsell' },
  { label: 'Clearance - move old stock', value: 'clearance' },
];

const TONE_OPTIONS = [
  {
    label: 'Professional',
    value: 'Professional - formal, business-appropriate language',
  },
  {
    label: 'Friendly',
    value: 'Friendly - warm, approachable, and conversational',
  },
  {
    label: 'Casual',
    value: 'Casual - relaxed, informal, like talking to a friend',
  },
  {
    label: 'Enthusiastic',
    value: 'Enthusiastic - energetic, excited, positive vibes',
  },
  {
    label: 'Helpful',
    value: 'Helpful - supportive, solution-oriented, empathetic',
  },
  {
    label: 'Persuasive',
    value: 'Persuasive - convincing, compelling, sales-focused',
  },
  {
    label: 'Informative',
    value: 'Informative - educational, factual, detailed explanations',
  },
  { label: 'Witty', value: 'Witty - clever, humorous, playful with words' },
];

const CampaignCreate = (): JSX.Element => {
  const navigate = useNavigate();

  const [categories, setCategories] = useState<string[]>([]);
  const [loadingCategories, setLoadingCategories] = useState(false);

  const [formName, setFormName] = useState('');
  const [selectedCategories, setSelectedCategories] = useState<Set<string>>(
    new Set()
  );
  const [formDescription, setFormDescription] = useState('');
  const [formPriority, setFormPriority] = useState('balanced');
  const [formGoal, setFormGoal] = useState('conversion');
  const [formTone, setFormTone] = useState(
    'Friendly - warm, approachable, and conversational'
  );
  const [formMinPrice, setFormMinPrice] = useState('');
  const [formMaxPrice, setFormMaxPrice] = useState('');
  const [discountCodes, setDiscountCodes] = useState<ICampaignDiscountCode[]>(
    []
  );
  const [dcCode, setDcCode] = useState('');
  const [dcDescription, setDcDescription] = useState('');
  const [dcValue, setDcValue] = useState('');
  const [dcType, setDcType] = useState<'percentage' | 'fixed'>('percentage');
  const [dcMaxUses, setDcMaxUses] = useState('');
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [categorySearch, setCategorySearch] = useState('');

  const fetchCategories = useCallback(async () => {
    try {
      setLoadingCategories(true);
      const response = await getCategories();
      if (!response.errors && response.data) {
        setCategories(response.data.categories || []);
      }
    } catch (err: any) {
      setError(err?.message || 'Failed to load categories');
    } finally {
      setLoadingCategories(false);
    }
  }, []);

  useEffect(() => {
    fetchCategories();
  }, [fetchCategories]);

  const toggleCategory = (cat: string) => {
    setSelectedCategories(prev => {
      const next = new Set(prev);
      if (next.has(cat)) {
        next.delete(cat);
      } else {
        next.add(cat);
      }
      return next;
    });
  };

  const filteredCategories = categorySearch
    ? categories.filter(c =>
        c.toLowerCase().includes(categorySearch.toLowerCase())
      )
    : categories;

  const selectAll = () => {
    setSelectedCategories(new Set(filteredCategories));
  };

  const deselectAll = () => {
    setSelectedCategories(new Set());
  };

  const handleCreate = async () => {
    if (!formName.trim() || selectedCategories.size === 0) return;

    const payload: ICreateCampaignPayload = {
      name: formName.trim(),
      target_categories: Array.from(selectedCategories),
      description: formDescription.trim(),
      priority: formPriority as 'soft' | 'balanced' | 'strong',
      goal: formGoal as ICreateCampaignPayload['goal'],
      tone_of_voice: formTone,
      min_price: formMinPrice ? parseFloat(formMinPrice) : null,
      max_price: formMaxPrice ? parseFloat(formMaxPrice) : null,
      discount_codes: discountCodes.length > 0 ? discountCodes : undefined,
    };

    try {
      setCreating(true);
      setError(null);
      await createCampaign(payload);
      navigate('/campaigns');
    } catch (err: any) {
      setError(err?.message || 'Failed to create campaign');
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="w-full max-w-5xl mx-auto p-5">
      <div className="space-y-5">
        {/* Header */}
        <div className="flex justify-between items-center">
          <h1 className="text-xl font-bold text-gray-900">Create Campaign</h1>
          <button
            className="px-4 py-2 bg-white border border-gray-300 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50 transition-colors"
            onClick={() => navigate('/campaigns')}
          >
            Back
          </button>
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex justify-between items-center">
            <p className="text-sm">{error}</p>
            <button
              className="text-red-500 hover:text-red-700 text-sm"
              onClick={() => setError(null)}
            >
              Dismiss
            </button>
          </div>
        )}

        {/* Campaign details */}
        <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
          <h2 className="text-base font-semibold text-gray-900">
            Campaign Details
          </h2>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Campaign Name
            </label>
            <input
              type="text"
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
              value={formName}
              onChange={e => setFormName(e.target.value)}
              placeholder="e.g. Winter Sale 2026"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Description
            </label>
            <textarea
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
              value={formDescription}
              onChange={e => setFormDescription(e.target.value)}
              placeholder="e.g. 20% off all winter items, limited time only"
              rows={3}
            />
            <p className="text-xs text-gray-500 mt-1">
              Short description - AI will generate sales rules from this
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Priority
            </label>
            <select
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
              value={formPriority}
              onChange={e => setFormPriority(e.target.value)}
            >
              {PRIORITY_OPTIONS.map(o => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Campaign Goal
            </label>
            <select
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
              value={formGoal}
              onChange={e => setFormGoal(e.target.value)}
            >
              {GOAL_OPTIONS.map(o => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Tone of Voice
            </label>
            <select
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
              value={formTone}
              onChange={e => setFormTone(e.target.value)}
            >
              {TONE_OPTIONS.map(o => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Min Price
              </label>
              <input
                type="number"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={formMinPrice}
                onChange={e => setFormMinPrice(e.target.value)}
                placeholder="e.g. 10"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Max Price
              </label>
              <input
                type="number"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={formMaxPrice}
                onChange={e => setFormMaxPrice(e.target.value)}
                placeholder="e.g. 500"
              />
            </div>
          </div>
        </div>

        {/* Discount Codes */}
        <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
          <h2 className="text-base font-semibold text-gray-900">
            Discount Codes
          </h2>
          <p className="text-xs text-gray-500">
            Add discount codes the AI can offer to customers. Codes are
            distributed using round-robin (least used first).
          </p>

          {discountCodes.length > 0 && (
            <div className="space-y-2">
              {discountCodes.map((dc, i) => (
                <div key={dc.code} className="flex items-center gap-3">
                  <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                    {dc.code}
                  </span>
                  <span className="text-sm text-gray-700">
                    {dc.description}
                  </span>
                  <span className="text-sm text-gray-500">
                    {dc.type === 'percentage'
                      ? `${dc.value}%`
                      : `${dc.value} fixed`}
                    {dc.max_uses ? ` · max ${dc.max_uses} uses` : ''}
                  </span>
                  <button
                    className="text-xs text-red-600 hover:text-red-800"
                    onClick={() =>
                      setDiscountCodes(prev => prev.filter((_, j) => j !== i))
                    }
                  >
                    Remove
                  </button>
                </div>
              ))}
            </div>
          )}

          <div className="flex items-end gap-2 flex-wrap">
            <div className="flex-[2] min-w-[100px]">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Code
              </label>
              <input
                type="text"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={dcCode}
                onChange={e => setDcCode(e.target.value)}
                placeholder="WINTER20"
              />
            </div>
            <div className="flex-[3] min-w-[140px]">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description
              </label>
              <input
                type="text"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={dcDescription}
                onChange={e => setDcDescription(e.target.value)}
                placeholder="20% off winter items"
              />
            </div>
            <div className="flex-1 min-w-[80px]">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Value
              </label>
              <input
                type="number"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={dcValue}
                onChange={e => setDcValue(e.target.value)}
                placeholder="20"
              />
            </div>
            <div className="flex-1 min-w-[80px]">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Type
              </label>
              <select
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={dcType}
                onChange={e =>
                  setDcType(e.target.value as 'percentage' | 'fixed')
                }
              >
                <option value="percentage">%</option>
                <option value="fixed">Fixed</option>
              </select>
            </div>
            <div className="flex-1 min-w-[80px]">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Max uses
              </label>
              <input
                type="number"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                value={dcMaxUses}
                onChange={e => setDcMaxUses(e.target.value)}
                placeholder="100"
              />
            </div>
            <button
              className="px-3 py-2 text-sm font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
              disabled={!dcCode.trim() || !dcValue}
              onClick={() => {
                setDiscountCodes(prev => [
                  ...prev,
                  {
                    code: dcCode.trim(),
                    description: dcDescription.trim(),
                    value: parseFloat(dcValue) || 0,
                    type: dcType,
                    max_uses: dcMaxUses ? parseInt(dcMaxUses) : 0,
                    used_count: 0,
                  },
                ]);
                setDcCode('');
                setDcDescription('');
                setDcValue('');
                setDcMaxUses('');
              }}
            >
              Add
            </button>
          </div>
        </div>

        {/* Category selection */}
        <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
          <div className="flex justify-between items-center">
            <h2 className="text-base font-semibold text-gray-900">
              Target Categories
            </h2>
            {selectedCategories.size > 0 && (
              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                {selectedCategories.size} selected
              </span>
            )}
          </div>

          <p className="text-xs text-gray-500">
            Select which product categories this campaign should promote. The AI
            agent will prioritize these products in chat conversations.
          </p>

          {loadingCategories ? (
            <div className="flex justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
            </div>
          ) : categories.length === 0 ? (
            <div className="bg-yellow-50 border border-yellow-200 text-yellow-700 px-4 py-3 rounded-lg">
              <p className="text-sm">
                No product categories found. Make sure your products have been
                imported.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              <div className="relative">
                <input
                  type="text"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                  value={categorySearch}
                  onChange={e => setCategorySearch(e.target.value)}
                  placeholder="Search categories..."
                />
                {categorySearch && (
                  <button
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    onClick={() => setCategorySearch('')}
                  >
                    &times;
                  </button>
                )}
              </div>

              <div className="flex items-center gap-2">
                <button
                  className="px-3 py-1 text-xs font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                  onClick={selectAll}
                >
                  Select All ({filteredCategories.length})
                </button>
                <button
                  className="px-3 py-1 text-xs font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                  onClick={deselectAll}
                >
                  Deselect All
                </button>
              </div>

              <div
                className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2"
                style={{ maxHeight: '400px', overflowY: 'auto' }}
              >
                {filteredCategories.map(cat => (
                  <div
                    key={cat}
                    className="border rounded-lg p-2 cursor-pointer hover:bg-gray-50 transition-colors"
                    onClick={() => toggleCategory(cat)}
                    style={{
                      backgroundColor: selectedCategories.has(cat)
                        ? '#f0f7ff'
                        : undefined,
                      borderColor: selectedCategories.has(cat)
                        ? '#2c6ecb'
                        : undefined,
                    }}
                  >
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={selectedCategories.has(cat)}
                        onChange={() => toggleCategory(cat)}
                        className="rounded border-gray-300"
                      />
                      <span className="text-sm text-gray-700">{cat}</span>
                    </label>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Submit */}
        <div className="flex justify-end gap-2">
          <button
            className="px-4 py-2 bg-white border border-gray-300 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50 transition-colors"
            onClick={() => navigate('/campaigns')}
          >
            Cancel
          </button>
          <button
            className="px-4 py-2 bg-gray-900 text-white text-sm font-medium rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-50"
            disabled={
              !formName.trim() || selectedCategories.size === 0 || creating
            }
            onClick={handleCreate}
          >
            {creating ? 'Creating...' : 'Create Campaign'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default CampaignCreate;
