/**
 * BOM Detail Page
 * View BOM details
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { productionAPI } from '@/lib/api/production';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
  Modal,
} from '@/components/ui';
import { formatDate, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, Edit, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { useState } from 'react';

export default function BOMDetailPage() {
  const router = useRouter();
  const params = useParams();
  const bomId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // Fetch BOM details
  const { data: bom, isLoading, error } = useQuery({
    queryKey: ['bom', bomId],
    queryFn: async () => {
      if (isNaN(bomId)) {
        throw new Error('Invalid BOM ID');
      }
      const response = await productionAPI.getBOM(bomId);
      return response?.data || response;
    },
    enabled: !isNaN(bomId),
  });

  const deleteBOMMutation = useMutation({
    mutationFn: async () => {
      return await productionAPI.deleteBOM(bomId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['boms']);
      toast.success('BOM deleted successfully!');
      router.push('/production/boms');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to delete BOM';
      toast.error(message);
      setShowDeleteModal(false);
    },
  });

  const handleDelete = () => {
    deleteBOMMutation.mutate();
  };

  if (isLoading) {
    return <LoadingPage message="Loading BOM details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!bom) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>BOM not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to BOMs
        </Button>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => router.push(`/production/boms/${bomId}/edit`)}
            className="flex items-center gap-2"
          >
            <Edit className="w-4 h-4" />
            Edit
          </Button>
          <Button
            variant="outline"
            onClick={() => setShowDeleteModal(true)}
            className="flex items-center gap-2 text-red-600 hover:text-red-700"
          >
            <Trash2 className="w-4 h-4" />
            Delete
          </Button>
        </div>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle>BOM Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">BOM Information</h3>
              <p className="text-gray-600 dark:text-gray-400 mb-2">
                <span className="font-medium">FG Product:</span>{' '}
                {bom.finishedGoodProduct?.name || bom.finishedGood?.name || bom.fgProduct?.name || 'Unknown'}
              </p>
              {bom.finishedGoodProduct?.sku || bom.finishedGood?.sku || bom.fgProduct?.sku ? (
                <p className="text-gray-600 dark:text-gray-400 mb-2">
                  <span className="font-medium">SKU:</span> {bom.finishedGoodProduct?.sku || bom.finishedGood?.sku || bom.fgProduct?.sku}
                </p>
              ) : null}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Information</h3>
              <p className="text-gray-600 dark:text-gray-400 mb-2">
                <span className="font-medium">Raw Materials:</span>{' '}
                <Badge variant="info">{bom.items?.length || 0} items</Badge>
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Created:</span> {formatDateTime(bom.created_at)}
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Updated:</span> {formatDateTime(bom.updated_at)}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {bom.items && bom.items.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Raw Materials</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Item Type</TableHead>
                  <TableHead>Raw Material</TableHead>
                  <TableHead>SKU</TableHead>
                  <TableHead align="right">Requirements</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {bom.items.map((item) => {
                  // Check if dimension-based by presence of dimension fields
                  const isDimensionBased = !!(item.required_length || item.required_width || item.dimension_unit);
                  const product = item.rawMaterial;
                  
                  return (
                    <TableRow key={item.id}>
                      <TableCell>
                        <Badge variant="primary">{item.item_type || 'FABRIC'}</Badge>
                      </TableCell>
                      <TableCell className="font-medium">
                        {product?.name || 'Unknown'}
                      </TableCell>
                      <TableCell>
                        {product?.sku || '—'}
                      </TableCell>
                      <TableCell align="right">
                        {isDimensionBased ? (
                          <div className="text-right">
                            <div className="font-medium">
                              {item.required_length} × {item.required_width} {item.dimension_unit || 'm'}
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              Area: {(parseFloat(item.required_length || 0) * parseFloat(item.required_width || 0)).toFixed(2)} {item.dimension_unit || 'm'}² per unit
                            </div>
                          </div>
                        ) : (
                          <div className="text-right">
                            <div className="font-medium">
                              {item.quantity_per_unit} {product?.unit_of_measure ? product.unit_of_measure : 'units'}
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              per unit of finished good
                            </div>
                          </div>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="Delete BOM"
        description={`Are you sure you want to delete this BOM? This action cannot be undone.`}
      >
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" onClick={() => setShowDeleteModal(false)}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleDelete}
            disabled={deleteBOMMutation.isLoading}
            loading={deleteBOMMutation.isLoading}
            className="bg-red-600 hover:bg-red-700"
          >
            Delete
          </Button>
        </div>
      </Modal>
    </div>
  );
}

