All files / src/components/features/admin/dev/DevTicketForm index.tsx

0% Statements 0/844
100% Branches 0/0
0% Functions 0/1
0% Lines 0/844

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { clientLogger } from '@/lib/logging/clientLogger';
import {
  DEV_TICKET_TYPE_CONFIG,
  DEV_TICKET_STATUS_CONFIG,
  DEV_TICKET_PRIORITY_CONFIG,
  DEV_TICKET_SEVERITY_CONFIG,
  DEV_TICKET_CATEGORY_CONFIG,
  CATEGORY_HIERARCHY_RULES,
  STORY_POINT_OPTIONS } from '@/constants/dev-ticket';
import type {
  DevTicketType,
  DevTicketStatus,
  DevTicketPriority,
  DevTicketSeverity,
  DevTicketCategory } from '@/types/dev-ticket';

interface Project {
  id: string;
  name: string;
  key: string;
}

interface Sprint {
  id: string;
  name: string;
}

interface Milestone {
  id: string;
  name: string;
}

interface User {
  id: number;
  name: string | null;
  email: string;
}

interface Label {
  id: string;
  name: string;
  color: string;
}

interface ParentTicket {
  id: string;
  ticketNumber: string;
  title: string;
  category: DevTicketCategory;
  projectId?: string | null;
  sprintId?: string | null;
  milestoneId?: string | null;
}

// Get the default child category for a given parent category
function getDefaultChildCategory(parentCategory: DevTicketCategory): DevTicketCategory {
  switch (parentCategory) {
    case 'EPIC':
      return 'PHASE';
    case 'PHASE':
      return 'STORY';
    case 'STORY':
      return 'TASK';
    case 'TASK':
      return 'SUBTASK';
    default:
      return 'TASK';
  }
}

interface TicketFormData {
  title: string;
  description: string;
  type: DevTicketType;
  status: DevTicketStatus;
  priority: DevTicketPriority;
  severity: DevTicketSeverity | null;
  category: DevTicketCategory;
  parentId: string | null;
  objectives: string;
  definitionOfDone: string;
  projectId: string | null;
  sprintId: string | null;
  milestoneId: string | null;
  assigneeId: number | null;
  estimatedHours: number | null;
  storyPoints: number | null;
  dueDate: string;
  labelIds: string[];
}

interface DevTicketFormProps {
  ticketId?: string;
  initialParentId?: string;
}

export default function DevTicketForm({ ticketId, initialParentId }: DevTicketFormProps) {
  const router = useRouter();
  const isEdit = !!ticketId;

  const [loading, setLoading] = useState(isEdit);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [projects, setProjects] = useState<Project[]>([]);
  const [sprints, setSprints] = useState<Sprint[]>([]);
  const [milestones, setMilestones] = useState<Milestone[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [labels, setLabels] = useState<Label[]>([]);
  const [parentTickets, setParentTickets] = useState<ParentTicket[]>([]);
  const [parentSearchQuery, setParentSearchQuery] = useState('');
  const [parentDataLoaded, setParentDataLoaded] = useState(false);

  const [formData, setFormData] = useState<TicketFormData>({
    title: '',
    description: '',
    type: 'TASK',
    status: 'OPEN',
    priority: 'MEDIUM',
    severity: null,
    category: 'TASK',
    parentId: initialParentId || null,
    objectives: '',
    definitionOfDone: '',
    projectId: null,
    sprintId: null,
    milestoneId: null,
    assigneeId: null,
    estimatedHours: null,
    storyPoints: null,
    dueDate: '',
    labelIds: []});

  // Get allowed parent categories for the current category
  const allowedParentCategories = useMemo(() => {
    return CATEGORY_HIERARCHY_RULES[formData.category] || [];
  }, [formData.category]);

  // Filter parent tickets by allowed categories
  const filteredParentTickets = useMemo(() => {
    return parentTickets.filter(ticket => {
      // Filter by allowed parent category
      if (!allowedParentCategories.includes(ticket.category)) return false;
      // Filter by search query
      if (parentSearchQuery) {
        const query = parentSearchQuery.toLowerCase();
        return (
          ticket.title.toLowerCase().includes(query) ||
          ticket.ticketNumber.toLowerCase().includes(query)
        );
      }
      return true;
    });
  }, [parentTickets, allowedParentCategories, parentSearchQuery]);

  // Selected parent ticket info
  const selectedParent = useMemo(() => {
    if (!formData.parentId) return null;
    return parentTickets.find(t => t.id === formData.parentId) || null;
  }, [formData.parentId, parentTickets]);

  useEffect(() => {
    fetchOptions();
    if (isEdit) {
      fetchTicket();
    } else if (initialParentId && !parentDataLoaded) {
      fetchParentAndSetDefaults();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ticketId, initialParentId, parentDataLoaded]);

  // Fetch parent ticket data and set default values for child ticket
  const fetchParentAndSetDefaults = async () => {
    if (!initialParentId) return;

    try {
      const response = await fetch(`/api/dev/tickets/${initialParentId}`);
      if (!response.ok) {
        clientLogger.error('Failed to fetch parent ticket', new Error('Failed to fetch parent ticket'), { initialParentId });
        return;
      }

      const data = await response.json();
      const parent = data.data;

      // Set form defaults based on parent
      const childCategory = getDefaultChildCategory(parent.category);

      setFormData(prev => ({
        ...prev,
        parentId: initialParentId,
        category: childCategory,
        projectId: parent.projectId || null,
        sprintId: parent.sprintId || null,
        milestoneId: parent.milestoneId || null,
        assigneeId: parent.assigneeId || null}));

      // Load project sprints and milestones if parent has a project
      if (parent.projectId) {
        fetchProjectData(parent.projectId);
      }

      setParentDataLoaded(true);
    } catch (err) {
      clientLogger.error('Error fetching parent ticket', err instanceof Error ? err : new Error(String(err)), { initialParentId });
    }
  };

  const fetchOptions = async () => {
    try {
      const [projectsRes, labelsRes, parentTicketsRes] = await Promise.all([
        fetch('/api/dev/projects?isActive=true'),
        fetch('/api/dev/labels'),
        fetch('/api/dev/tickets?limit=500&fields=id,ticketNumber,title,category'),
      ]);

      if (projectsRes.ok) {
        const data = await projectsRes.json();
        setProjects(data.data || []);
      }

      if (labelsRes.ok) {
        const data = await labelsRes.json();
        setLabels(data.data || []);
      }

      if (parentTicketsRes.ok) {
        const data = await parentTicketsRes.json();
        setParentTickets(data.data || []);
      }

      // Fetch admin users for assignee
      const usersRes = await fetch('/api/admin/users?role=ADMIN');
      if (usersRes.ok) {
        const data = await usersRes.json();
        setUsers(data.data || data.users || []);
      }
    } catch (err) {
      clientLogger.error('Error fetching options', err instanceof Error ? err : new Error(String(err)));
    }
  };

  const fetchTicket = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/dev/tickets/${ticketId}`);

      if (!response.ok) {
        setError('Failed to load ticket');
        return;
      }

      const data = await response.json();
      const ticket = data.data;

      setFormData({
        title: ticket.title,
        description: ticket.description,
        type: ticket.type,
        status: ticket.status,
        priority: ticket.priority,
        severity: ticket.severity,
        category: ticket.category || 'TASK',
        parentId: ticket.parentId,
        objectives: ticket.objectives || '',
        definitionOfDone: ticket.definitionOfDone || '',
        projectId: ticket.projectId,
        sprintId: ticket.sprintId,
        milestoneId: ticket.milestoneId,
        assigneeId: ticket.assigneeId,
        estimatedHours: ticket.estimatedHours,
        storyPoints: ticket.storyPoints,
        dueDate: ticket.dueDate ? ticket.dueDate.split('T')[0] : '',
        labelIds: ticket.labels?.map((l: Label) => l.id) || []});

      // Load sprints and milestones for the project
      if (ticket.projectId) {
        fetchProjectData(ticket.projectId);
      }
    } catch (err) {
      setError('Failed to load ticket');
      clientLogger.error('Error fetching ticket', err instanceof Error ? err : new Error(String(err)), { ticketId });
    } finally {
      setLoading(false);
    }
  };

  const fetchProjectData = async (projectId: string) => {
    try {
      const [sprintsRes, milestonesRes] = await Promise.all([
        fetch(`/api/dev/sprints?projectId=${projectId}`),
        fetch(`/api/dev/milestones?projectId=${projectId}`),
      ]);

      if (sprintsRes.ok) {
        const data = await sprintsRes.json();
        setSprints(data.data || []);
      }

      if (milestonesRes.ok) {
        const data = await milestonesRes.json();
        setMilestones(data.data || []);
      }
    } catch (err) {
      clientLogger.error('Error fetching project data', err instanceof Error ? err : new Error(String(err)), { projectId });
    }
  };

  const handleChange = (field: keyof TicketFormData, value: unknown) => {
    setFormData(prev => ({ ...prev, [field]: value }));

    if (field === 'projectId' && value) {
      fetchProjectData(value as string);
      setFormData(prev => ({ ...prev, sprintId: null, milestoneId: null }));
    }

    // Reset parentId when category changes (allowed parents may change)
    if (field === 'category') {
      const newCategory = value as DevTicketCategory;
      const newAllowedParents = CATEGORY_HIERARCHY_RULES[newCategory] || [];
      setFormData(prev => {
        // Check if current parent is still valid
        if (prev.parentId) {
          const currentParent = parentTickets.find(t => t.id === prev.parentId);
          if (currentParent && !newAllowedParents.includes(currentParent.category)) {
            return { ...prev, parentId: null };
          }
        }
        return prev;
      });
    }
  };

  const handleLabelToggle = (labelId: string) => {
    setFormData(prev => ({
      ...prev,
      labelIds: prev.labelIds.includes(labelId)
        ? prev.labelIds.filter(id => id !== labelId)
        : [...prev.labelIds, labelId]}));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError(null);

    try {
      const url = isEdit ? `/api/dev/tickets/${ticketId}` : '/api/dev/tickets';
      const method = isEdit ? 'PATCH' : 'POST';

      // Build payload, excluding null/empty values for create (API expects undefined, not null)
      const payload: Record<string, unknown> = {
        title: formData.title,
        description: formData.description,
        type: formData.type,
        priority: formData.priority,
        category: formData.category};

      // Only include optional fields if they have values
      if (formData.severity) payload.severity = formData.severity;
      if (formData.parentId) payload.parentId = formData.parentId;
      if (formData.objectives) payload.objectives = formData.objectives;
      if (formData.definitionOfDone) payload.definitionOfDone = formData.definitionOfDone;
      if (formData.projectId) payload.projectId = formData.projectId;
      if (formData.milestoneId) payload.milestoneId = formData.milestoneId;
      if (formData.sprintId) payload.sprintId = formData.sprintId;
      if (formData.assigneeId) payload.assigneeId = formData.assigneeId;
      if (formData.estimatedHours) payload.estimatedHours = formData.estimatedHours;
      if (formData.storyPoints) payload.storyPoints = formData.storyPoints;
      if (formData.dueDate) payload.dueDate = new Date(formData.dueDate).toISOString();
      if (formData.labelIds.length > 0) payload.labelIds = formData.labelIds;

      // For edit mode, include status
      if (isEdit) {
        payload.status = formData.status;
      }

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)});

      if (!response.ok) {
        const data = await response.json();
        setError(data.error || 'Failed to save ticket');
        return;
      }

      const data = await response.json();
      router.push(`/admin/dev/tickets/${data.data.id}`);
    } catch (err) {
      setError('Failed to save ticket');
      clientLogger.error('Error saving ticket', err instanceof Error ? err : new Error(String(err)));
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/3 mb-8"></div>
          <div className="space-y-4">
            <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
            <div className="h-32 bg-gray-200 dark:bg-gray-700 rounded"></div>
            <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 mb-2">
          <Link href="/admin/dev" className="hover:text-gray-700 dark:hover:text-gray-300">Dev</Link>
          <span>/</span>
          <Link href="/admin/dev/tickets" className="hover:text-gray-700 dark:hover:text-gray-300">Tickets</Link>
          <span>/</span>
          <span className="text-gray-900 dark:text-gray-100">{isEdit ? 'Edit' : 'New'}</span>
        </div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
          {isEdit ? 'Edit Ticket' : 'Create New Ticket'}
        </h1>
      </div>

      {error && (
        <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg text-red-700 dark:text-red-300">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Title */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Title <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            value={formData.title}
            onChange={e => handleChange('title', e.target.value)}
            required
            minLength={5}
            maxLength={200}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            placeholder="Brief description of the ticket"
          />
        </div>

        {/* Description */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Description <span className="text-red-500">*</span>
          </label>
          <textarea
            value={formData.description}
            onChange={e => handleChange('description', e.target.value)}
            required
            minLength={10}
            rows={10}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
            placeholder="Detailed description (Markdown supported)"
          />
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">Markdown formatting is supported</p>
        </div>

        {/* Type and Status */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Type</label>
            <select
              value={formData.type}
              onChange={e => handleChange('type', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              {Object.entries(DEV_TICKET_TYPE_CONFIG).map(([value, config]) => (
                <option key={value} value={value}>
                  {config.icon} {config.label}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Status</label>
            <select
              value={formData.status}
              onChange={e => handleChange('status', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              {Object.entries(DEV_TICKET_STATUS_CONFIG).map(([value, config]) => (
                <option key={value} value={value}>
                  {config.label}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Priority and Severity */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Priority</label>
            <select
              value={formData.priority}
              onChange={e => handleChange('priority', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              {Object.entries(DEV_TICKET_PRIORITY_CONFIG).map(([value, config]) => (
                <option key={value} value={value}>
                  {config.icon} {config.label}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Severity</label>
            <select
              value={formData.severity || ''}
              onChange={e => handleChange('severity', e.target.value || null)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              <option value="">None</option>
              {Object.entries(DEV_TICKET_SEVERITY_CONFIG).map(([value, config]) => (
                <option key={value} value={value}>
                  {config.icon} {config.label}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Hierarchy Section */}
        <div className="border-t dark:border-gray-700 pt-6 mt-6">
          <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Hierarchy</h3>

          {/* Category and Parent */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Category
                <span className="ml-1 text-xs text-gray-500 dark:text-gray-400">(Work Item Level)</span>
              </label>
              <select
                value={formData.category}
                onChange={e => handleChange('category', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                {Object.entries(DEV_TICKET_CATEGORY_CONFIG).map(([value, config]) => (
                  <option key={value} value={value}>
                    {config.icon} {config.label}
                  </option>
                ))}
              </select>
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                {DEV_TICKET_CATEGORY_CONFIG[formData.category]?.description}
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Parent Ticket
                {allowedParentCategories.length > 0 && (
                  <span className="ml-1 text-xs text-gray-500 dark:text-gray-400">
                    (can be under: {allowedParentCategories.join(', ')})
                  </span>
                )}
              </label>
              {allowedParentCategories.length === 0 ? (
                <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-500 dark:text-gray-400 text-sm">
                  {formData.category === 'EPIC' ? 'Epics are root-level items' : 'No parent allowed for this category'}
                </div>
              ) : (
                <div className="relative">
                  <input
                    type="text"
                    placeholder="Search tickets..."
                    value={parentSearchQuery}
                    onChange={e => setParentSearchQuery(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  />
                  {selectedParent && (
                    <div className="mt-2 p-2 bg-indigo-50 dark:bg-indigo-900/30 border border-indigo-200 dark:border-indigo-700 rounded-lg flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <span className="text-xs">
                          {DEV_TICKET_CATEGORY_CONFIG[selectedParent.category]?.icon}
                        </span>
                        <span className="text-sm font-medium text-indigo-800 dark:text-indigo-300">
                          {selectedParent.ticketNumber}
                        </span>
                        <span className="text-sm text-indigo-600 dark:text-indigo-400 truncate max-w-[200px]">
                          {selectedParent.title}
                        </span>
                      </div>
                      <button
                        type="button"
                        onClick={() => handleChange('parentId', null)}
                        className="text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 text-sm"
                      >
                        Clear
                      </button>
                    </div>
                  )}
                  {!selectedParent && filteredParentTickets.length > 0 && (
                    <div className="mt-1 max-h-48 overflow-y-auto border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 shadow-sm">
                      {filteredParentTickets.slice(0, 10).map(ticket => (
                        <button
                          key={ticket.id}
                          type="button"
                          onClick={() => {
                            handleChange('parentId', ticket.id);
                            setParentSearchQuery('');
                          }}
                          className="w-full px-3 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-2 border-b dark:border-gray-700 last:border-b-0"
                        >
                          <span className="text-xs">
                            {DEV_TICKET_CATEGORY_CONFIG[ticket.category]?.icon}
                          </span>
                          <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                            {ticket.ticketNumber}
                          </span>
                          <span className="text-sm text-gray-600 dark:text-gray-400 truncate">
                            {ticket.title}
                          </span>
                        </button>
                      ))}
                      {filteredParentTickets.length > 10 && (
                        <div className="px-3 py-2 text-xs text-gray-500 dark:text-gray-400 text-center">
                          +{filteredParentTickets.length - 10} more - refine your search
                        </div>
                      )}
                    </div>
                  )}
                  {!selectedParent && filteredParentTickets.length === 0 && parentSearchQuery && (
                    <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      No matching parent tickets found
                    </p>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* Objectives */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Objectives
              <span className="ml-1 text-xs text-gray-500 dark:text-gray-400">(What should this achieve?)</span>
            </label>
            <textarea
              value={formData.objectives}
              onChange={e => handleChange('objectives', e.target.value)}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
              placeholder="- Reduce bundle size by 30%&#10;- Improve Time to Interactive (TTI)"
            />
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">List the goals this ticket aims to accomplish</p>
          </div>

          {/* Definition of Done */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Definition of Done
              <span className="ml-1 text-xs text-gray-500 dark:text-gray-400">(Completion criteria)</span>
            </label>
            <textarea
              value={formData.definitionOfDone}
              onChange={e => handleChange('definitionOfDone', e.target.value)}
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm"
              placeholder="- [ ] Bundle size < 200KB&#10;- [ ] TTI < 3 seconds on 3G&#10;- [ ] All tests passing"
            />
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">Checklist of criteria that must be met (Markdown supported)</p>
          </div>
        </div>

        {/* Project, Sprint, Milestone */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Project</label>
            <select
              value={formData.projectId || ''}
              onChange={e => handleChange('projectId', e.target.value || null)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              <option value="">No Project</option>
              {projects.map(project => (
                <option key={project.id} value={project.id}>
                  [{project.key}] {project.name}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Sprint</label>
            <select
              value={formData.sprintId || ''}
              onChange={e => handleChange('sprintId', e.target.value || null)}
              disabled={!formData.projectId}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:bg-gray-100 dark:disabled:bg-gray-800"
            >
              <option value="">No Sprint</option>
              {sprints.map(sprint => (
                <option key={sprint.id} value={sprint.id}>
                  {sprint.name}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Milestone</label>
            <select
              value={formData.milestoneId || ''}
              onChange={e => handleChange('milestoneId', e.target.value || null)}
              disabled={!formData.projectId}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:bg-gray-100 dark:disabled:bg-gray-800"
            >
              <option value="">No Milestone</option>
              {milestones.map(milestone => (
                <option key={milestone.id} value={milestone.id}>
                  {milestone.name}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Assignee and Due Date */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Assignee</label>
            <select
              value={formData.assigneeId || ''}
              onChange={e => handleChange('assigneeId', e.target.value ? parseInt(e.target.value) : null)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              <option value="">Unassigned</option>
              {users.map(user => (
                <option key={user.id} value={user.id}>
                  {user.name || user.email}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Due Date</label>
            <input
              type="date"
              value={formData.dueDate}
              onChange={e => handleChange('dueDate', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
        </div>

        {/* Estimated Hours and Story Points */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Estimated Hours</label>
            <input
              type="number"
              min="0"
              step="0.5"
              value={formData.estimatedHours || ''}
              onChange={e => handleChange('estimatedHours', e.target.value ? parseFloat(e.target.value) : null)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              placeholder="e.g., 4"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Story Points</label>
            <select
              value={formData.storyPoints || ''}
              onChange={e => handleChange('storyPoints', e.target.value ? parseInt(e.target.value) : null)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            >
              <option value="">None</option>
              {STORY_POINT_OPTIONS.map(points => (
                <option key={points} value={points}>
                  {points}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Labels */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Labels</label>
          <div className="flex flex-wrap gap-2">
            {labels.map(label => (
              <button
                key={label.id}
                type="button"
                onClick={() => handleLabelToggle(label.id)}
                className={`px-3 py-1 rounded-full text-sm font-medium transition-all ${
                  formData.labelIds.includes(label.id)
                    ? 'ring-2 ring-offset-2 ring-indigo-500'
                    : 'opacity-60 hover:opacity-100'
                }`}
                style={{
                  backgroundColor: label.color + '30',
                  color: label.color}}
              >
                {label.name}
              </button>
            ))}
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center justify-end gap-4 pt-4 border-t">
          <Link
            href={isEdit ? `/admin/dev/tickets/${ticketId}` : '/admin/dev/tickets'}
            className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            Cancel
          </Link>
          <button
            type="submit"
            disabled={saving}
            className="px-6 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 disabled:opacity-50"
          >
            {saving ? 'Saving...' : isEdit ? 'Update Ticket' : 'Create Ticket'}
          </button>
        </div>
      </form>
    </div>
  );
}